[Ruby] What does 'yield' do in plain english?
Bob Marley
mlee1024 at gmail.com
Fri Jun 8 10:13:25 PDT 2007
Thanks all for the help.. upon further readings I found a clearer example
that worked for me. I need to step back from rails and read more about ruby.
Pretty cool language trick.
again thanks for the feedback
miene
F:\>irb -r irb/completion
irb(main):001:0> def takeBlock(p1)
irb(main):002:1> if block_given?
irb(main):003:2> yield(p1)
irb(main):004:2> else
irb(main):005:2* p1
irb(main):006:2> end
irb(main):007:1> end
=> nil
irb(main):008:0> takeBlock("Not gonna yield")
=> "Not gonna yield"
irb(main):009:0> takeBlock("Not gonna yield"){|x| puts "ZOMG Lies: "+x}
ZOMG Lies: Not gonna yield
=> nil
irb(main):010:0>
On 6/7/07, Harry Dean Hudson Jr. <dean at ero.com> wrote:
>
> On 6/7/07, Fruchterman, Thomas <tfrucht at amazon.com> wrote:
> > Yield means "call the block that was passed into the function with the
> > following arguments".
>
> Another example that makes a lot of sense to me is Array#each. To
> implement Array#each with a for loop you could do something like this:
>
> irb(main):001:0> class Array
> irb(main):002:1> def new_each
> irb(main):003:2> for i in self
> irb(main):004:3> yield i
> irb(main):005:3> end
> irb(main):006:2> end
> irb(main):007:1> end
> => nil
> irb(main):008:0> f = [1,2,3]
> => [1, 2, 3]
> irb(main):009:0> f.new_each {|i| puts i}
> 1
> 2
> 3
> => [1, 2, 3]
>
> In this case new_each stepped through the array and called the given
> block ({|i| puts i}) once for each element by yielding execution to
> that block in the for loop (and passing it i).
>
> Using it once makes sense because the behavior of the code calling
> yield is dependent on the block of code that you pass it. The
> degenerate example is:
>
> def do_block
> yield
> end
>
> which just executes whatever block you pass it,
>
> do_block {puts 'foo'}
>
> will just puts "foo."
>
> hope that helps,
> dean.
> _______________________________________________
> Ruby at zenspider.com - Seattle.rb non-commercial list
> http://www.zenspider.com/seattle.rb
> http://www.zenspider.com/mailman/listinfo/ruby
>
More information about the Ruby
mailing list