: Iterators are nothing but methods supported by collections. Objects that store a group of data members are called collections. In Ruby, arrays and hashes can be termed collections. Iterators return all the elements of a collection, one after the other. We will be discussing two iterators here, each and collect. Let's look at these in detail.
.each : which can apply an expression to each element of an object, one at a time.
for i in 1..10
print i, " "
end
# => 1 2 3 4 5 6 7 8 9 10
# Compare this with upto, which does exactly the same thing:
1.upto(10) { |i| print i, " " }
# => 1 2 3 4 5 6 7 8 9 10
[1, 2, 3].respond_to?(:push)
# => true (.push on an array object)
[1, 2, 3].respond_to?(:to_sym)
# => false (can't turn an array into a symbol.)
:hello.is_a? Symbol
# ==> true
def method_name(argument, *argu)
# Do something!
return someting
end
method_name(argument)
def hello(names)
names.each do |n|
puts "Hello, #{n.upcase}"
end
end
rubies = %w[MRI jruby rubinius]
hello(rubies)
def block_test
puts "We're in the method!"
puts "Yielding to the block..."
yield
puts "We're back in the method!"
end
block_test { puts ">>> We're in the block!" }
# => We're in the method!
Yielding to the block...
>>> We're in the block!
We're back in the method!
nil
def double(num)
yield num
end
double(2) { |n| n*2 }
# => 4