tags:

views:

348

answers:

2

I have a Builder class that lets you add to one of it's 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"]

Into this?

my_builder = Builder.new
my_builder.lines {
    add_line "foo"
    add_line "bar"
}
p my_builder.lines # => ["foo", "bar"]
+9  A: 
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"]
khelll
Couldn't be any more perfect. Thank you!
c00lryguy
A: 

You can also use the method use in ruby best practice using the length of 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

sasuke