1

我有几个类用于在 Ruby 中包含数据(及其上的一些方法)。例如:

class Foo
  def initialize(bar, biz, baz)
    @bar=bar
    @biz=biz
    @baz=baz
  end
end

将这些初始化参数传播到实例变量中是否有较少重复的方法?

4

3 回答 3

2

一个班轮,但我发现这会掩盖一些事情:

@bar,@biz,@baz = bar,biz,baz
于 2013-11-11T04:19:24.943 回答
1
class Foo
  def initialize(*args)
    raise ArgumentError unless args.length == 3
    @bar, @biz, @baz = args
  end
end
于 2013-11-11T04:19:31.800 回答
0

一种快速的方法是使用Struct

class Foo < Struct.new(:bar, :biz, :baz)
  # custom methods go here
end

Struct.new 将返回一个为您设置了初始化程序和访问器的类(除此之外,它只是一个普通类)。如果您不需要任何自定义方法,您还可以定义一个结构内联(例如Foo = Struct.new(:bar, :biz, :baz))。

于 2013-11-11T04:42:35.963 回答