Ruby Programming/Reference/Built-in Modules

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

[edit] Enumerable

[edit] each_with_index

each_with_index calls its block with the item and its index.

array = ['Superman','Batman','The Hulk']

array.each_with_index do |item,index|
  puts "#{index} -> #{item}"
 end

# will print
# 0 -> Superman
# 1 -> Batman
# 2 -> The Hulk

[edit] find_all

find_all returns only those items for which the called block is not false

range = 1 .. 10

# find the even numbers

array = range.find_all { |item| item % 2 == 0 }

# returns [2,4,6,8,10]
array = ['Superman','Batman','Catwoman','Wonder Woman']

array = array.find_all { |item| item =~ /woman/ }

# returns ['Catwoman','Wonder Woman']