Eval Within Block Instance

I have a Builder class that allows you to add to one of its instance variables:

class Builder
    def initialize
        @lines = []
    end

    def lines
        block_given? ? yield(self) : @lines
    end

    def add_line( text )
        @lines << text
    end
end

Now how do i change this

my_builder = Builder.new
my_builder.lines { |b|
    b.add_line "foo"
    b.add_line "bar"
}
p my_builder.lines # => ["foo", "bar"]

In it?

my_builder = Builder.new
my_builder.lines {
    add_line "foo"
    add_line "bar"
}
p my_builder.lines # => ["foo", "bar"]
+5
source share
2 answers
class Builder
    def initialize
        @lines = []
    end

    def lines(&block)
        block_given? ? instance_eval(&block) : @lines
    end

    def add_line( text )
        @lines << text
    end
end

my_builder = Builder.new
my_builder.lines {
    add_line "foo"
    add_line "bar"
}
p my_builder.lines # => ["foo", "bar"]
+12
source

You can also use the use of the method in Ruby, using the length of the arguments with arity:

class foo

attr_accessor :list

def initialize
   @list=[]
end

def bar(&blk)

  blk.arity>0 ? blk.call(self) : instance_eval(&blk)

end

end

x = Foo.new

x.bar do list <1 list <2 list <3 end

x.bar do | foo | foo.list <4 foo.list <5 foo.list <6 end

puts x.list.inspect

+1
source

All Articles