1

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 comments.

I'm not sure how to do this problem at all. I'm especially new to block and yield.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user487743
  • 2,145
  • 4
  • 16
  • 11

1 Answers1

3
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"] 
fl00r
  • 82,987
  • 33
  • 217
  • 237
  • Thank you! I think I understand what is going on. – user487743 Apr 12 '11 at 01:35
  • there is some differences between using `do..end` and `{}` braces. check out http://stackoverflow.com/questions/5587264/do-end-vs-curly-braces-for-blocks-in-ruby and related posts on SO. It will be useful – fl00r Apr 12 '11 at 12:45