Ruby: Method Help
I am a computer science major, and we are just learning Ruby. I am very lost on this problem we are supposed to solve, mostly syntax issues. Here is what we are to do:
Write a method that takes an array of strings and a block and calls this block on each string. Recall that the keyword to call a block is yield. The syntax for the call is the following:
method(["blah", "Blah"]) {...}
Test the method by passing it a block that prints the result of applying reverse to each string. Print out the original array after the call. Test it again by passing a block that calls reverse!. Print out the original array. Observe the differences, explain them in com开发者_如何转开发ments.
I'm not sure how to do this problem at all. I'm especially new to block and yield.
def my_method(array, &block)
array.each{|a| yield a}
end
array = ["one", "two", "three"]
my_method(array) do |a|
puts a.reverse
end
#=> eno
#=> owt
#=> eerht
array
#=> ["one", "two", "three"]
my_method(array) do |a|
puts a.reverse!
end
#=> eno
#=> owt
#=> eerht
array
#=> ["eno", "owt", "eerht"]
精彩评论