ruby减少重复

时间:2011-02-16 00:09:18

标签: ruby

class Car
    attr_accessor :door, :window, :engine, :wheel, :mirror, :seat...
end

my_car = Car.new
my_car.door, my_car.window, my_car.engine, my_car.wheel = "door", "window", "engine", "wheel"

我不想重复输入my_car。我知道我可以定义initialize(door, window, engine, wheel),但还有其他方法吗?像

这样的东西
my_car.METHOD do
    door, window, engine, wheel = "door", "window", "engine", "wheel"
end

5 个答案:

答案 0 :(得分:2)

您可以在构造函数中执行此操作:

class Car
  attr_accessor :door, :window, :engine, :wheel, :mirror

  def initialize(opts={})
     opts.each {|k,v| self.send("#{k}=", v)}
  end
end

然后,您可以在对象创建时提供所有选项:

my_car = Car.new(:door => "4dr", :engine => "2.4L")

p my_car
#<Car:0x8a585f4 @door="4dr", @engine="2.4L">

答案 1 :(得分:1)

对于'的问题部分,还有其他任何方式':

此表格

my_car.METHOD do
  door, window, engine, wheel = "door", "window", "engine", "wheel"
end

类似于 instance_eval ,它在对象的上下文中计算块:

my_car.instance_eval do
  @door = "door"
  @window = "window"
end

P.S。不是在争论它是否是最好的方式,但是:)

答案 2 :(得分:0)

%w(door window) |f|
    my_car.send(f + "=", "some string, possibly f itself like the next line")
    my_car.send(f + "=", f)
end

答案 3 :(得分:0)

也许facets可以帮助你: Module.assign

然后这将是:

my_car.assign( :door => "door", :window => "window" .... )

答案 4 :(得分:0)

您实际上可以定义yield initialize:

def initialize(&block)
  instance_eval(&block)
end

然后

my_car = Car.new do
  @door = "door"
  @window = "window"
  #...
end

你必须使用@attr,因为像“var = value”这样的语句会假设你设置了一个新的本地变体。