Reputation: 572
So, I'm not seeing exactly what I'm looking for in the search. Here's my question. I'm learning Ruby and RoR right now - and I've got a question I can't seem to find the answer to. So, here's my play code:
class BlocksAndIterators
def yield_madness(a, b)
my_funky_pi = ((a*b) - (b+a)) / 3.14
my_yield = yield(my_funky_pi, a)
"my_funky_pi: #{my_funky_pi}\nmy_yield: #{my_yield}"
end
end
bi = BlocksAndIterators.new
puts bi.yield_madness(12, 24){|x, y| puts "x: #{x} and y: #{y}"}
Now, the output I'm getting is as follows:
dkm@dkm-MasterControl:~/Projects/ruby_playground$ ruby blocks_iterators.rb
x: 80.2547770700637 and y: 12
my funky pi: 80.2547770700637
my yield:
so my question is this - does yield not actually return anything in the traditional sense? I'm not getting any errors here, so I don't think I'm doing anything syntactically incorrect - but my_yield doesn't seem to be returning what it seems it should. Is there a way to capture the output of yield to a variable? Is this just something you would never do? I'm just playing around with code here, but I thought this should have been something that might work shrugs At any rate - thanks for anyone who answers :)
Upvotes: 2
Views: 1654
Reputation: 7349
The problem you're having is that your block returns the result of the puts
, which is nil
, and in a string winds up being an empty string. use a different block, for example this, and you get a different result:
puts bi.yield_madness(12, 24) { |x, y|
puts "x: #{x} and y: #{y}"
32
}
x: 80.2547770700637 and y: 12
my_funky_pi: 80.2547770700637
my_yield: 32
=> nil
Upvotes: 3