简体   繁体   中英

Instance Eval Within Block

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM