Just yesterday I wrote about Enumerable and some of its all-stars. Well, here’s another baller: inject. It took me a bit to truly grok and appreciate this method, but once I did it really cleaned up my code and mind. Zen-like.

Injecting the Comic Book Example
Previously I wanted to find all objects in an array with an item_type equal to Comic (as opposed to Poems).
Here was my first stab:
books = Book.find(:all, :order => 'id desc', :limit => 20) comics = [] books.each do |book| comics << book if book.item_type == 'Comic' end
I cleaned this up with select, but here’s how someone might accomplish this task using inject:
books = Book.find(:all, :order => 'id desc', :limit => 20) comics = books.inject([]) do |array, book| if book.item_type == 'Comic' array + [book] else array end end
This code’ll give me a new array, comics, consisting only of Book objects whose item_type is Comic. How?
In Ruby
As the Apple Rails page says, “The inject method is a Ruby idiom for accumulating while stepping through a collection of objects.” Correct. Here’s how I’d write inject:
# inject's parameter is optional, but let's keep things simple def inject(target) each do |element| target = yield(target, element) end target end
You pass inject a target and a block. The block is passed two elements: the target (which you are injecting) and the current element in your collection. The target is replaced each step of the way by what the block returns as it iterates over your collection. What you’re left with is a beefed up, injected target.
Summing Numbers
The canonical inject example seems to be summing up a range of numbers. Not one to break convention, here you go:
>> (0..10).inject(0) { |sum, number| sum + number } => 55
For fun and profit, concoct your very own sum method:
module Enumerable def sum inject { |sum, number| sum + number } end end >> (0..10).sum => 55 >> [1,2,3,4].sum => 10
If you don’t pass it a parameter, inject will fill its target with the first element of the collection, skipping that element.
Hey, that factorial function everyone’s always throwing around? Trivial.
def factorial(x) return 1 if x.zero? (1..x).inject { |a, b| a * b } end
Even and Odd
Here’s another example: we want all the even numbers from 0 to 10:
evens = (0..10).inject([]) do |array, number| if number % 2 == 0 array + [number] else array end end
Again, our array local variable gets replaced each step of the way by the result of the block. If it’s not an even number, we just return the array as it stands. Be warned: if we returned nil inside of the block we’d run into problems as within the next iteration array would be nil.
Hashes, too
All this haxin’ makes me hungry. I need to find places to eat that aren’t any more than 10 minutes away. Because inject is a method on Enumerable, we can use it with hashes as well:
>> distance_of_food = { :pizza => 10, :thai => 21, :indian => 11, :mexican => 9, :burgers => 15 } => {:pizza=>10, :thai=>21, :indian=>11, :mexican=>9, :burgers=>15} >> distance_of_food.inject({}) do |hash, (place, distance)| key = distance <= 10 ? :near : :far hash[key] ||= [] hash[key] << place hash end => {:near=>[:pizza, :mexican], :far=>[:thai, :indian, :burgers]}
Remember to always end the block with the new value of your target (hash in this case) and also make sure to break out the key and value parameters with parenthesis in your block if iterating over a hash.
Instance Variables to_hash
Want to get a hash of instance variables from an object you’re coding? inject makes it easy:
class Restaurant def initialize(type, minutes_away) @type, @minutes_away = type, minutes_away end def to_hash instance_variables.inject({}) do |hash, ivar| hash.merge(ivar.gsub('@','') => instance_variable_get(ivar)) end end end >> cybelles_pizza = Restaurant.new('pizza', 10) => #<Restaurant:0x4d56c0 @minutes_away=10, @type="pizza"> >> cybelles_pizza.to_hash => {"type"=>"pizza", "minutes_away"=>10}
Glorious.
A More Complex Example
This one uses some Rails code, group_by. If you’re unfamiliar you can get the scoop in this post.
comments = Comment.find(:all, :order => 'id desc', :limit => 30) comments.group_by(&:item_type).inject({}) do |hash, (type, items)| hash.merge(type => type.constantize.find(items.map(&:item_id))) end
What we end up with is a hash keyed by item_type with each member containing an array of items which correspond to that item_type. Not so bad.
injecting
Here’s a little tidbit Ezra was cool enough to share with me: injecting. Try it out:
module Enumerable def injecting(s) inject(s) do |k, i| yield(k, i); k end end end
As he explains, here’s one way to collect a hash:
>> [1,2,3,4,5].inject({}) {|m, el| m[el] = el; m } => {5=>5, 1=>1, 2=>2, 3=>3, 4=>4}
With injecting you needn’t worry about explicitly returning the target—it’s done for you:
>> [1,2,3,4,5].injecting({}) {|m, el| m[el] = el } => {5=>5, 1=>1, 2=>2, 3=>3, 4=>4}
Pretty handy. (By the way, why m? Because the target I keep referring to is commonly known as the memo. Take note.)
Finally, const_grabbin’
One last thing to share. This is pretty neat, from Dave Thomas’ annotate_models plugin:
class_name.split('::').inject(Object) do |klass, part| klass.const_get(part) end
This code is turning a string like Blogs::Grinder into a constant. Think about it. Real slick.
More More More
For more uses of inject, check the ever handy RDoc. Gregory Brown blogged about it on the O’Reilly blog back in July, and then there’s the minimal ruby+inject tag on delicious (which could use some love). Check that page and you’ll see that, as always, Projectionist does not disappoint.
Got any more crazy uses of inject? Hit me up. Pastie for best results. Thanks, yes.
Update: Greggory Bluvshteyn teaches me maths and fixes my factorial method.
As usual, great post, thanks!
Excellent write up. With all the Rails loving going on, people often forget about the loveliness that is Ruby. It’s great seeing people injecting (heh, get the pun…) some enthusiasm back into the mother tongue :-)
Big fan of yours man, keep rolling. Just the special case for factorial though (0)
Nevertheless this inject method is pretty awsome def factorial(x) return (1..x).inject { |a, b| a * b } if x != 0 return 1 if x == 0 end
Great post. I’m learning so much from your posts, I can’t thank you enough!
While I was reading the code snippet using inject for getting the odd numbers out of an array, I was concerned by creating a new array for each iteration with an odd number (array + [number]). So I wrote a small bench using inject, select and a combination of map and compact. It turns out that using inject is much slower.
ar = (1..1000000).to_a
For select, I am using: evens = ar.select {|number| number % 2 0 }
For map/compact I am using: evens = ar.map {|number| (number % 2 0) ? number : nil } evens.compact!
I just wanted to share those results with you (array contains numbers from 1 to 1,000,000): - inject: 10.621 seconds - select: 0.056 seconds - map/compact: 0.0606 seconds
The results are also exponentials: it will take 2ms for 1,000 numbers, 116ms for 10,000, 10.621 secs for 100,000, 41 secs for 1,000,000. Whereas for select and map/compact methods, the results are pretty linear (from 0.5 ms for 1,000 to 112 ms for 1,000,000).
Thanks for the benchmarks, Zlaj! Useful to know that inject is not the answer if speed is an issue.
Here’s my example – using inject with logic operations: http://offtheline.net/2007/1/27/ruby-inject-and-logic-operations For example, if you have an array and you want to know if each item in the array passes a given test, collectively, or check to see if any of those items passes the test (e.g. is this user a member of any of these groups?)
Nice post Chris.
Let me make a small remark on your way to mimic “select” using “inject”: you could make it faster by pushing each element matching the condition into the injected array instead of adding it to an array composed of a sole matching element. Like this:
Fold is a better name than inject. it is the same thing execpt it’s shorter and it is more functional sounding.
I agree that inject is slow, at least for a hash to be the product. After switching to “a = {}; b.each…”-solution from a inject I got a speed down to 1% of the inject-version.
Some other speed increases (not related to inject):
I tried to use the built in solution for escaping strings for mysql but got a huge slowdown with my page, it took 3 sec for it to escape 6000 strings!books = Book.find(:all, :order => ‘id desc’, :limit => 20) comics = books.inject([]) do |array, book| if book.item_type == ‘Comic’ array + [book] else array end end
Why not
... comics = books.reject { |x| x.item_type != ‘Comic’ }
?
Good funny jokes good jokes great post thanks
Tattoos Celtic Tattoos Lower Back Tattoos Dragon Tattoos Skull Tattoos Heart Tattoos Butterfly Tattoos Chinese Tattoos Layered Hair Styles Layered Hairstyles Emo Hairstyles Medium Hairstyles Bang Hairstyle Prom Hairstyle Hair Coloring Heart Lower Back Tattoos
sikiş porno sex video izle iyi porno uzun porno yeni pornolar porno seyret sex seyret porno filmler sex izleyin sex izle porno sex erotik porn video türk porno canlı porno porno izle porno porno film sex filmleri porn video porno film sex seyret porno video seyret orgazm porno seks izle erotik video sex videolar yetişkin video sex video izle porno video izle bedava porno 18 video seks porno sıcak izle yetişkin film sikiş seyret sex amatör videolar teen video erotik videolar yetişkin video yetişkin videolar pornolar porno video teen kızlık bozma sikiş sikiş video seks türban sex sex erotik seks izle sıcak ateşli
modern abstract art sofa manufacturer гранит 净水器 混合机 过滤机 DHL快递 保险箱 法兰 法兰标准 牛皮癣 皮肤病 北京快递公司 北京国际快递 传世私服 传奇世界私服 天龙八部私服 天龙私服 网络电话 免费网络电话 假发 补发 织发 植发 上海搬家公司 上海搬场公司 大众搬家 大众搬场 张家界旅游 香港旅游 深圳旅行社 打包机 收缩机 萎缩性胃炎 neoprene laptop bags SEO优化 SEO优化 计量泵 胃炎 胃病 冷水机 冰水机 工业冷水机 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 北京办证 办证 北京特价机票 北京打折计票 北京国际机票 北京机票预定 北京飞机票 北京订机票 北京机票查询 血糖仪 血糖仪 银杏 水培花卉 企业宣传片 空分设备 机电设备安装 代孕 代孕网 代孕 代孕 代孕 试管婴儿 代孕 电话交换机 程控交换机 集团电话 集装袋 混合机混合机 混合机捏合机 捏合机 捏合机导热油炉 导热油炉 导热油炉 反应釜 反应釜 反应釜 回流焊 波峰焊 spherical roller bearing 搬运车 搬运车 电动搬运车 油桶搬运车 堆高车 电动堆高车 半电动堆高车 堆垛车 高空作业平台车 电动叉车 平衡重叉车 前移叉车 电瓶叉车 苗木价格 苗木信息 标牌制作 深圳标牌 儿童摄影 北京儿童摄影 防静电鞋 淘宝刷信誉 威海凤凰湖 威海海景房 大庆密封件 打标机 淘宝刷信誉 TESOL/TEFL国际英语教师证书 英语教师进修及培训 韩国饰品批发 代写论文 代写论文 代写论文 代写代发 论文代写 电源模块 模块电源 X架 超薄灯箱> 易拉宝 展柜制作 代理服务器 游戏加速器 网络加速器 网通加速器 电信加速器 电信网通转换器 电信网通加速器 网通电信互转 网通电信互通 网络游戏加速器 美国VPN代理 美国独享VPN 美国独享IP pvc ceiling panel Spherical roller bearings 天龙八部私服 SEO优化 安全鞋 劳保鞋 防砸鞋 电绝缘鞋 上海安全鞋 上海劳保鞋 江苏劳保鞋 服装软件 服装管理软件 进销存软件 进销存管理软件 服装管理系统 服装进销存软件 进销存系统 进销存管理系统 免费进销存软件 吉林中医 东北特产 打包机 dhl 阳痿 阴茎短小 阴茎增大 早泄 前列腺炎 阴茎增粗 阴茎延长 国际机票 上海国际机票 国际打折机票 国际特价机票 CRM 客户管理软件 客户关系管理 免费客户管理软件 客户管理软件下载 客户信息管理系统 销售管理系统 销售管理 CRM系统 CRM软件 客户关系管理系统 客户关系管理软件 客户管理 客户管理系统 营销管理系统 客户资源管理 销售管理软件 客户资料管理软件 客户资源管理软件 客户信息管理软件 客户资料管理 客户资源管理 客户信息管理 客户资料管理系统 客户资源管理系统 客户管理软件免费版 砂磨机 砂磨机 砂磨机 卧式砂磨机 卧式砂磨机 卧式砂磨机 三辊研磨机 三辊研磨机 三辊研磨机 混合机 混合机 混合机 锥形混合机 锥形混合机 锥形混合机 行星动力混合机 行星动力混合机 行星动力混合机 无重力混合机 无重力混合机 无重力混合机 干粉砂浆设备 干粉砂浆设备 干粉砂浆设备 捏合机 捏合机 捏合机 导热油炉 导热油炉 导热油炉 反应釜 反应釜 反应釜 搪玻璃反应釜 搪玻璃反应釜 搪玻璃反应釜 乳化机 涂料设备 干混砂浆设备 无重力混合机 胶体磨 涂料成套设备 双螺旋混合机 北京婚庆 北京婚庆公司 400电话 办证 呼吸机 制氧机 亚都 亚都加湿器 亚都净化器 亚都装修卫士 饰品批发 小饰品批发 韩国饰品 韩国饰品批发 premature ejaculation penis enlargement 破碎机 制砂机 球磨机 雷蒙磨 雷蒙磨粉机 鄂式破碎机 鄂式破碎机 免烧砖机 加气混凝土设备 反击式破碎机 选矿设备 安利产品 马来西亚留学 网站优化 网站推广 衬布 代写论文 代写论文 代写论文 论文代写 代写论文 代写硕士论文 代写毕业论文 磁力泵 离心泵 化工泵 隔膜泵 螺杆泵 潜水泵 油泵 耐腐蚀泵 泵 水泵 拖链 防护罩 排屑机 塑料拖链 钢铝拖链 水泵 磁力泵 隔膜泵 离心泵 液下泵 自吸泵 多级泵 排污泵 螺杆泵 油泵 化工泵 电动隔膜泵 气动隔膜泵 自吸式磁力泵 氟塑料磁力泵 管道离心泵 导热油泵 深井泵 潜水泵 污水泵 潜水排污泵 深圳装饰 深圳装饰公司 深圳装修公司 特价机票 打折机票 国际机票 机票 新风换气机 换气机 立式新风换气机 风机箱 新风系统 能量回收机 搅拌机 混合机 乳化机 分散机 毛刷 毛刷辊 工业毛刷 刷子 钢丝刷 涂层测厚仪 硬度计 兆欧表 激光测距仪 测振仪 转速表 温湿度计 风速仪 超声波测厚仪 粗糙度仪 噪音计 红外测温仪 万用表 硬度计 万用表 美容院 美容加盟 澳洲留学 澳大利亚留学 什么是法兰 电烤箱 酒店预定 北京酒店预定 北京酒店 离心机 nail equipment nail products nail product nail uv lamp nail uv lamp nail uv lamps uv nail lamp nail brush nail file nail tool nail tip nail gel curing uv lamps lights 万用表 风速仪 红外测温仪 噪音计
情趣用品,情趣用品,情趣用品,情趣用品,情趣用品,情趣,情趣,情趣,情趣,情人歡愉用品,情惑用品性哥,情人用品性哥,情趣用品,AIO交友愛情館,情人歡愉用品,美女視訊,情色交友,情人用品性哥,視訊交友,辣妹視訊,美女交友,性愛,嘟嘟成人網,按摩棒,震動按摩棒,微調按摩棒,情趣按摩棒,逼真按摩棒,G點,跳蛋,跳蛋,跳蛋,性感內衣,飛機杯,充氣娃娃,情趣娃娃,角色扮演,性感睡衣,後庭區,SM,潤滑液,情趣禮物,威而柔,香水,精油,芳香精油,自慰,自慰套,性感吊帶襪,情趣用品加盟,情人節禮物,情人節,吊帶襪,辣妹視訊,美女交友,情色交友,成人交友,視訊聊天室,美女視訊,視訊美女,情色視訊,免費視訊聊天,視訊交友,視訊聊天,AIO交友愛情館,嘟嘟成人網,成人貼圖,成人網站,AIO交友愛情館,情色,情色貼圖,情色文學,情色交友,色情聊天室,色情小說,七夕情人節,色情,A片,A片下載,免費A片,免費A片下載,情色視訊,情色電影,色情網站,辣妹視訊,視訊聊天室,情色視訊,免費視訊聊天,視訊聊天,美女視訊,視訊美女,美女交友,美女,情色交友,成人交友,自拍,本土自拍,情人視訊網,視訊交友90739,生日禮物,情色論壇,正妹牆,正妹,成人網站,A片,免費A片,A片下載,免費A片下載,AV女優,成人影片,色情A片,成人論壇,情趣,免費成人影片,成人電影,成人影城,愛情公寓,色情影片,保險套
Thanks so much for this! This is exactly what I was looking for
mirc mırc mırç mirç mirc indir mirc yükle mirc yukle türkçe mirc mirc indir mirc islami sohbet kelebek kelebek script kelebek sohbet kelebek mirc chat çet cet çet odaları sohbet kanalları sohbet odaları kameralı sohbet kameralı chat sohbet eğlence mirc sohbet odaları sevgili arkadaş arkadaş bul arkaraş ara oto araba şarkı sözleri astroloji ikinci el telefon gazete gazeteler günlük gazeteler marifetname bedava domain ücretsiz domain benimurl parça kontör parça kontör radyo dinle bedava blog ücretsiz blog
video ödev indir şarkı sözleri video izle şiir türkü indir güzel sözler fıkra porno izle pornolar 18
Victorias Secret Victoria’s Secret Fashion show Victorias Secret Pink Victorias Secret Model Victorias Secret Credit Card Victorias Secret Coupon Code Victorias Secret Lingerie Victorias Secret Fashion Show 2005 Victorias Secret Fashion Show 2006 Victorias Secret Bra Victorias Secret Catalog Victorias Secret Pantie Victorias Secret Online Coupon Victorias Secret Fashion Show 2007 Victorias Secret Girl Free Shipping Victorias Secret Victorias Secret Home Victorias Secret Christmas Victoria’S Secret Pink Dog Victorias Secret Music Victorias Secret Semi Annual Sale Victorias Secret Jobs Victorias Secret Free Shipping Code Victorias Secret Shoes Victorias Secret Thong Victorias Secret Commercial Victorias Secret Promotional Code Victorias Secret Love Spell Victorias Secret Boots Victorias Secret Employment Victorias Secret Reviews Victorias Secret Jeans Victorias Secret Brasil Victorias Secret Bag
情人用品,情人用品性哥,情 人用品,情趣用品,視訊交友,視訊美女,視訊美女,視訊交友網,視訊聊天室,視訊聊天室,視訊 交友網,免費視訊聊天,辣妹視訊,辣妹視訊,情人視訊網
徵信社,案件討論,男女專區,法律諮詢,相關新聞,情趣用品,情趣用品,情趣精品,情趣用品,情趣用品,情趣用品,情趣用品,威而柔,自慰套,自慰套,SM,充氣娃娃,充氣娃娃,潤滑液,飛機杯,按摩棒,跳蛋,性感睡衣
威而柔,自慰套,自慰套,SM,充氣娃娃,充氣娃娃,潤滑液,飛機杯,按摩棒,跳蛋,性感睡衣,視訊交友90739,情人視訊網,情色交友,視訊交友,辣妹視訊,美女視訊,aio交友愛情館,情色論壇,成人論壇,免費視訊聊天,辣妹視訊,視訊交友網,美女視訊,視訊交友,成人視訊,情趣用品,成人聊天室,情趣,情趣,視訊聊天室,視訊聊天,視訊聊天室,情色視訊,情人視訊網,免費視訊聊天室,aio交友愛情館,色情遊戲,寄情築園小遊戲,情色文學,一葉情貼圖片區
Chime in.