Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created August 17, 2011 19:24
Show Gist options
  • Save cowboy/1152377 to your computer and use it in GitHub Desktop.
Save cowboy/1152377 to your computer and use it in GitHub Desktop.
An example using "yield self if block_given?"
# No yielding
class NormPerson
attr_accessor :first, :last
def initialize(first = nil, last = nil)
@first = first
@last = last
end
def hello
puts "#{@first} #{@last} says hello!"
end
end
# You could do it like this...
ben = NormPerson.new("Ben", "Alman")
ben.hello # Ben Alman says hello!
# Or like this...
ben = NormPerson.new
ben.first = "Ben"
ben.last = "Alman"
ben.hello # Ben Alman says hello!
# (Optional) yielding
class YieldPerson
attr_accessor :first, :last
def initialize(first = nil, last = nil)
@first = first
@last = last
yield self if block_given?
end
def hello
puts "#{@first} #{@last} says hello!"
end
end
# While both of the previous ways work, so does this...
YieldPerson.new do |p|
p.first = "Ben"
p.last = "Alman"
p.hello # Ben Alman says hello!
end
@joshhubbard
Copy link

krivek007, I know this is extremelybold but just in case someone else sees this and was curious. The yield self is just a yield(self). It's passing itself as the parameter to the block statement. So when it says YieldPerson.new do |p|, that p is self. Thus it gets translated to

self.first = "Ben"
self.last = "Alman"
self.hello

That last line calls hello on it's self object and you get the output.

@youclavier
Copy link

This explanation is amazing!! I have been looking for a good explanation for yield self if block_given? , and after I read through this example, I finally truly understand!! Thank you so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment