首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Using select, reject, collect, inject and detect

2012-09-11 
Using select, reject, collect, inject and detect.?Looping in Ruby seems to be a process of evolutio

Using select, reject, collect, inject and detect.

?

Looping in Ruby seems to be a process of evolution for newcomers to the language. Newcomers will always find their way to the for loop almost immediately and when confronted with iterating an array, the first choice will generally be a for..in:

1234
123
12
12
12
12
12
12
12
a = [1,2,3,4]a.detect {|n| n == 3}

This returns 3. The value we were looking for. If the value had not been found, then the iterator returns?nil.

So if your head is spinning at this point as to which iterator to use for when, then remember this:

  1. Use select or reject if you need to select or reject items based on a condition.
  2. Use collect if you need to build an array of the results from logic in the block.
  3. Use inject if you need to accumulate, total, or concatenate array values together.
  4. Use detect if you need to find an item in an array.

By using these iterators you will be one step closer to mastering… Ruby-Fu.

?

热点排行