In Ruby, is there a way to accomplish what `with` does in Actionscript?

大城市里の小女人 提交于 2019-12-06 03:46:55
Hash.new.tap do |h|
  h[:name] = "Mike"
  h[:language] = "Ruby"
end
#=> {:name=>"Mike", :language=>"Ruby"} 

You could try Object#tap with Ruby 1.9.

So in your case:

board.tap do |b|
  b.length = 66;
  b.width = 19;
  b.fin_system = "lockbox"
end

One way to implement it is with instance_eval, like that:

def with(obj, &blk)
  obj.instance_eval(&blk)
end

a = "abc"
with a do
  self << 'b'
  gsub!('b', 'd')
  upcase!
end
puts a #=> ADCD

with board do 
  self.length = 66
  self.width = 19
  self.fin_system = 'lockbox'
end

But in some cases you have to use self (with operators and setting methods).

You can't accomplish that exactly in Ruby because foo = bar will always set a foo local variable; it will never call a foo= method. You can use tap as suggested.

One solution to the larger design question would be to use a fluent interface:

board.length(66).width(20)

class Board
  def length(amt)
    @length = amt
    self
  end

  def width(amt)
    @width = amt
    self
  end
end

It's up to you to decide if this pattern suits your use case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!