Computer Science Canada Fun with yield |
Author: | haskell [ Wed Dec 27, 2006 10:39 pm ] | ||||||||||||||
Post subject: | Fun with yield | ||||||||||||||
yield is possibly one of Ruby's most powerful features. It basically allows you to put a block of code into a function. This could be a value, a string, a regex, function call, etc... Consider:
Which results in 36. Or:
Which results in "ThY qYYck brYwn fYx jYmpYd YvYr thY lYzy dYg".
Trivial examples. But they show a potential(particularly in AI). So go off and experiment! |
Author: | rdrake [ Wed Dec 27, 2006 11:53 pm ] | ||||||||
Post subject: | Re: Fun with yield | ||||||||
haskell wrote: Consider:
Remember in Ruby the last value evaluated will also be the result returned by default.
Which results in 36. Consider:
![]() |
Author: | wtd [ Thu Dec 28, 2006 12:53 am ] | ||||
Post subject: | |||||
How about...
![]() |
Author: | rdrake [ Thu Dec 28, 2006 12:57 am ] | ||||
Post subject: | |||||
wtd wrote: How about...
Or...
![]()
|
Author: | haskell [ Thu Dec 28, 2006 1:05 pm ] | ||||||
Post subject: | More fun with yield | ||||||
Passing Values to Block Using yield
Which can also be dome as:
As you can see, the variable n of the pass_name method was passed to the block(do..end), and then used(under the new name, name, denoted by the | and | to be a variable of the block). The block could also have been done with brackets({ and }) instead of do ..end, but it is multi-lined, so do..end is the "standard". Have fun, and experiment ![]() |
Author: | wtd [ Thu Dec 28, 2006 1:11 pm ] | ||||
Post subject: | Re: More fun with yield | ||||
haskell wrote: Passing Values to Block Using yield
Or just:
I also find it mildly odd that you're not aware that "puts" automatically adds a newline as necessary. In your code, the newline you use is extraneous. |
Author: | haskell [ Thu Dec 28, 2006 1:47 pm ] |
Post subject: | |
I am aware. I just prefer to be explicit with my intentions. It doesn't make any difference in the output, but I know exactly what it will do without thinking about the function call(old habits die hard). I also use extra vars in the examples to show how vars can be passed using yield. Its not the passing of gets thats important in this example(thanks for the extra examples though). |
Author: | Clayton [ Fri Dec 29, 2006 9:14 am ] | ||||
Post subject: | |||||
okay, but afterwards, show how that can be streamlined by getting rid of uneeded "stuff". Follow this trivial example:
Can be shortened to:
Now, from a beginner's standpoint, the first makes more sense right? That's great, but they probably know that there has to be a better way of doing things, so then you show them, with the explanation of why it works exactly why it does. |