Kurt Peek
Kurt Peek

Reputation: 57761

In Ruby, perform a function on the contents of a block

As a Ruby programming exercise, I'd like to make a function "reverser" which reverse every word of a string. However, it should operator on the contents of a block and not on an argument. So

reverser {"hello dolly"}

should return "olleh yllod". I know how to make a similar method:

def reverse_words(string)
  words=string.split()
  words.map! {|word| word.reverse}
  words.join(" ")
end

However, the method should operate on the contents of a block and not on a 'normal' argument. So far I've got this:

def reverser(&prc)
  yield.reverse
end

However, this only reverses one word and not each word in a sentence. I'm not really sure how to get a 'handle' on the contents of the block passed as an argument in this way. Any ideas?

Upvotes: 1

Views: 60

Answers (2)

seph
seph

Reputation: 6076

def reverser
  yield.split.map(&:reverse)
end

reverser {"hello dolly"}
 => ["olleh", "yllod"] 

Upvotes: 5

Kurt Peek
Kurt Peek

Reputation: 57761

I found out that one can simply assign a variable to the output of "yield". So I defined

def reverser
  str=yield
  words=str.split()
  words.map! {|word| word.reverse}
  words.join(" ")
end

The command

p reverser {"hello dolly"}

Then leads to the desired output.

Upvotes: 1

Related Questions