I am learning Ruby, and for no particular reason, I want to pass the yield
object to the Integer#times method so that the yield
code block is called a number of times. Here is how I can do it with a named code block:
def withNamedCodeBlock &b
3.times(&b)
end
withNamedCodeBlock {print "Go "}
#returns Go Go Go
Now, I want to do the same, but without named code blocks; I want to do it with by using the yield
keyword. Here is how I tried and failed:
def withYield
3.times(&yield)
end
withYield {print "Go "}
#returns Go => #<Enumerator: 3:times>
#I expect it to return Go Go Go
I am still wrapping my head around the various ways to pass code blocks to methods, so additional information regarding that is appreciated.
Aucun commentaire:
Enregistrer un commentaire