Skip to content

Instantly share code, notes, and snippets.

@elskwid
Last active January 2, 2016 19:09
Show Gist options
  • Save elskwid/8348133 to your computer and use it in GitHub Desktop.
Save elskwid/8348133 to your computer and use it in GitHub Desktop.
Difference with capturing the block, yield with an argument, and yield
class WithBlockVar
attr_accessor :z
def initialize(x, &blk)
@x = x
instance_eval(&blk) if block_given?
end
end
# Using block variable
a = WithBlockVar.new("A") do
self.z = "Z"
end
puts a.inspect
# => #<WithBlockVar:0x007fa27c169470 @x="A", @z="Z">
class WithYieldArg
attr_accessor :z
def initialize(x)
@x = x
yield self if block_given?
end
end
# Using yield and block arg
b = WithYieldArg.new("B") do |b|
b.z = "Z"
end
puts b.inspect
# => #<WithYieldArg:0x007fa27c169218 @x="B", @z="Z">
class WithYield
attr_accessor :z
def initialize(x)
@x = x
yield if block_given?
end
end
# Using yield
c = WithYield.new("C") do
self.z = "Z"
end
puts c.inspect
# => block_yield.rb:39:in `block in <main>': undefined method `z=' for main:Object (NoMethodError)
# from block_yield.rb:21:in `initialize'
# from block_yield.rb:38:in `new'
# from block_yield.rb:38:in `<main>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment