tags:

views:

204

answers:

3

So I've got a Ruby method like this:

def something(variable, &block)
  ....
end

And I want to call it like this:

something 'hello' { do_it }

Except that isn't working for me, I'm getting a syntax error. If I do this instead, it works:

something 'hello' do
  do_it
end

Except there I'm kind of missing the nice look of it being on one line.

I can see why this is happening, as it could look like it's a hash being passed as a second variable, but without a comma in between the variables...but I assume that there must be a way to deal with this that I'm missing. Is there?

A: 

If you want "def something" to to accept a block, you need to yield data to that block. For example:

#to uppercase string
def something(my_input)
 yield my_input.upcase
end

# => "HELLO WORLD"
something("hello world") { |i| puts i}
bseanvt
That's not necessarily true. You could yield nothing, pass the block to another method, or choose to ignore it. There's not a specific need to yield anything to the block.The way the method in the original question was written, the block passwd will be converted to a `Proc` named `block`.
nertzy
+13  A: 

You need to parenthesize your argument:

something('hello') { do_it }

That should work.

Romulo A. Ceccon
yep, that does it!! Thanks. Sometimes it's the most obvious things you miss ;-)
Cameron Booth
@Cameron Booth: So maybe you can Accept his answer? :)
Pistos
A: 

Uh, what about:

>> def something(arg1 , &block)
>>   yield block
>> end
=> nil
>> def do_it
>>   puts "Doing it!"
>> end
=> nil
>> something('hello') { do_it }
"Doing it!"
=> nil
Ryan Bigg