I have a question about Ruby blocks.
For example I have a Ruby Class:
class NewClass
def initialize
@a = 1
end
def some_method
puts @a
end
end
When I do something like that:
NewClass.new do |c|
c.some_method
end
Everything is good, but is there any possibilities to do that somehow like:
NewClass.new do
some_method
end
Any ideas?
Your current code will just ignore the block anyway since you don’t
yieldto it. For what you are trying to do in your first example you need theyield selfidiom ininitialize.For why you need a block variable in the first place, think about what the receiver for
some_methodwould be in your second example. Without an explicit receiver it’s the top levelmain(unless this code is part of some other class of course, where that enclosing class would beself). See Dave Thomas’ blog post Changing self in Ruby (or Yehuda Katz’ post as pointed out by Niklas B. in the comments) for more info on that topic (the comments clear up the “proc invocation” part).Edit: all that said, this seems to work, but I prefer the
yield selfversion and example 1:This allows you to execute the block without a block variable and will return the new instance of the class for assigning to a variable etc.