-4

I use and work on Java and C#.
I was asked to explain Yield in following Ruby code.

Code:

mine=15
puts "Mine = 15"

def call_block  
   yield
   yield
puts 'Now for some magic!'  
end

call_block {mine}
print "Mine now is "
puts mine

Output:

mine = 15
now for some Magic!
mine now is 25

The question is how to get this output using the above code.
I don't know much about yield and that's why not getting the code right.
I think 10 has to be added somewhere but where?
Any help would be much appreciated.

Lalit Fauzdar
  • 5,953
  • 2
  • 26
  • 50
  • Have you read any online tutorials, or searched for "ruby yield"? What did you find? Why didn't they help? – the Tin Man May 25 '17 at 23:19
  • I did a quick search on yield and what i understood was that it was just an imaginary call for whatever reason to be changed later. I think the example i saw was they called yield and passed a variable with it and said its a place holder for later use? – sublimeaces May 25 '17 at 23:34
  • 1
    Did you run the code? What does it produce? How might you change the output of `call_block` to accomplish the goal? – Mark Thomas May 25 '17 at 23:39
  • 1
    Think of `z = yield(x,y)` as `z = execute_block(x,y)` where `x` and `y` are values to be assigned to the block's two block variables and `z` is assigned the value computed and returned by the block. – Cary Swoveland May 25 '17 at 23:51
  • `yield` is used (in one sense) in English as a verb meaning to _give way_ or _hand over_. In Ruby code we mean to yield to the block. – Sagar Pandya May 26 '17 at 00:03
  • It's my understanding that Java has anonmymous functions. That's basically what yield is. You allow a function to take a _block of code_ as an argument not just a value. See [/ruby-proccall-vs-yield](https://stackoverflow.com/questions/1410160/ruby-proccall-vs-yield) – max pleaner May 26 '17 at 01:23

1 Answers1

-1

Change {mine} to {mine+=5}. yield just executes it twice.

Bart
  • 2,606
  • 21
  • 32
  • @sublimeaces Point of what? `yield` is a syntactic sugar for executing a function that was passed as an argument. The other syntax would be to list it as `def call_block(&block)` and then perform a `block.call` twice. – Bart May 25 '17 at 23:46
  • There is no point for it in your example, but consider a sort method that accepts a custom sorting algorithm: `[1,2,3].sort_by{ |i| -i }` will perform a reverse sort – Bart May 25 '17 at 23:48
  • or a mapping method that takes a custom function to apply to every element: `[1,2,3].map{ |i| i + 10 } # => [11,12,13]` – Bart May 25 '17 at 23:52
  • Under the hood it did something like: `[yield(1), yield(2), yield(3)]` – Bart May 25 '17 at 23:53