class Test
def some_method
yield 'foo'
yield 'bar'
end
end
Test.new.some_method{|a| puts a}
foo
bar
=> nil
class Test
def some_method
yield 'foo', 'bar'
yield 'baz', 'bat'
end
end
Test.new.some_method{|a, b| puts "#{a} + #{b}"}
foo + bar
baz + bat
=> nil
class Test
include Enumerable
def each
yield 'foo', 'bar'
yield 'baz', 'bat'
end
end
Test.new.map{|a, b| a + ': ' + b}
=> ["foo: bar", "baz: bat"]
class MoreRealisticTest
attr_reader :collection1, :collection2
def initialize
@collection_a = ['foo', 'bat']
@collection_b = {
'foo' => 'bar',
'bat' => 'baz'
}
end
def my_pairs
@collection_a.each do | a |
yield a, @collection_b[a]
end
end
end
MoreRealisticTest.new.my_pairs do | a, b |
puts "#{a}: #{b}"
end
foo: bar
bat: baz
=> ["foo", "bat"]
Note that at this point, my_pairs
returning an Enumerator is probably more appropriate.
class Test
def my_map
my_array = []
my_array << yield(1)
my_array << yield(2)
end
end
Test.new.my_map{|x| x*x}
=> [1, 4]