大多数在线资料都有这样的初始化:
class MyClass
attr_accessors :a, :b, :c
def initialize(a,b,c)
@a = a
@b = b
@c = c
end
end
有或没有默认值。创建新实例是:
n = MyClass.new(1,2,3)
n.a # => 1
n.b # => 2
n.c # => 3
我想知道如何使用哈希语法初始化实例,例如:
n = MyClass.new(:a => 1, :b => 2, :c => 3)
应该相当于:
n = MyClass.new(:b => 2, :a => 1, :c => 3)
这难以实施吗?
答案 0 :(得分:9)
使用Ruby 2.0及以上版本中提供的ruby关键字参数
初始化参数中的格式为variable:
class MyClass
attr_accessors :a, :b, :c
def initialize(a:, b:, c: )
@a = a
@b = b
@c = c
end
end
答案 1 :(得分:0)
您在寻找以下内容吗?
class MyClass
attr_accessor :hash
def initialize(hash)
@hash = hash
end
end
e1 = MyClass.new(:a => 1, :b => 2, :c => 3)
#=> #<MyClass:0x007f88240d66b0 @hash={:a=>1, :b=>2, :c=>3}>
e1.hash
#=> {:a=>1, :b=>2, :c=>3}
e2 = MyClass.new( { :a => 1, :b => 2, :c => 3 } )
#=> #<MyClass:0x007f882281d678 @hash={:c=>3, :b=>2, :a=>1}>
e2.hash
#=> {:a=>1, :b=>2, :c=>3}
e3 = MyClass.new(:b => 2, :a => 1, :c => 3)
#=> #<MyClass:0x007f88240bd408 @hash={:b=>2, :a=>1, :c=>3}>
e3.hash
#=> {:b=>2, :a=>1, :c=>3}
e1
,e2
和e3
&#34;等效&#34;?
e1 == e2
#=> false
e1 == e3
#=> false
e1.hash == e2.hash
#=> true
e1.hash == e3.hash
#=> true
另一种看待这种情况的方法如下:
class MyClass
attr_accessor :args
def initialize(*args)
@args = args
end
end
e1 = MyClass.new(:a => 1, :b => 2, :c => 3)
#=> #<MyClass:0x007f88240d66b0 @hash={:a=>1, :b=>2, :c=>3}>
e1.args
#=> [{:a=>1, :b=>2, :c=>3}]
表示只有一个参数(哈希)被传递给new
。
答案 2 :(得分:0)
可以这么简单:
require 'ostruct'
class MyClass < OpenStruct
end
n = MyClass.new(:a => 1, :b => 2, :c => 3)
n.a
# => 1