She*_*acu 1 ruby instance-variables
我看到我的代码中一直出现这种情况
class Foo
def initialize(foo)
@foo = foo
end
#...
end
Run Code Online (Sandbox Code Playgroud)
这不是太糟糕,但它变得更糟:
class Foo
def initialize(foo,baz,bar,a,b,c,d)
@foo = foo
@baz = baz
@bar = bar
#etc...
Run Code Online (Sandbox Code Playgroud)
你可以通过做类似的事情来解决这个问题
@foo, @baz, @bar = foo, baz, bar
Run Code Online (Sandbox Code Playgroud)
但即使这样做感觉不对,也很烦人.有没有更好的方法根据参数定义实例变量?
编辑:这个问题似乎有2个不同的解决方案.看到:
您可能需要考虑使用Struct:
class Foo < Struct.new(foo,baz,bar,a,b,c,d)
end
foo = Foo.new(1,2,3,4,5,6,7)
foo.bar #=> 2
Run Code Online (Sandbox Code Playgroud)
initialize根本不需要定义额外的方法......
| 归档时间: |
|
| 查看次数: |
131 次 |
| 最近记录: |