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
@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