5

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"]

2 Answers 2

12
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"]
Sign up to request clarification or add additional context in comments.

1 Comment

Couldn't be any more perfect. Thank you!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.