Skip to content

Instantly share code, notes, and snippets.

@youclavier
Forked from cowboy/yield.rb
Created August 12, 2014 05:57
Show Gist options
  • Save youclavier/67b0a09517602eddd8d2 to your computer and use it in GitHub Desktop.
Save youclavier/67b0a09517602eddd8d2 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment