ruby中的哈希和函数参数

时间:2013-08-07 17:04:17

标签: ruby-on-rails ruby

我想写类似的东西:

class Test
  def initialize(a,b,c)
  end

  def print()
    puts @a
    puts @b
    puts @c
  end
end

Test.new({a=>1, b=>2, c=>3}).print()
=>1
=>2
=>3

有没有办法实例化对象并使用哈希表映射其参数?

提前致谢。

3 个答案:

答案 0 :(得分:4)

class Test
  def initialize(options)
    options.each do |key, value|
      instance_variable_set("@#{key}", value)
    end
  end

  def print
    puts @a
    puts @b
    puts @c
  end
end

Test.new(:a => 1, :b => 2, :c => 3).print

或使用OpenStruct

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ostruct/rdoc/OpenStruct.html

这是一个简单的例子:

require 'ostruct'

puts OpenStruct.new(:a => 1, :b => 2, :c => 3).inspect
# Outputs: "#<OpenStruct a=1, b=2, c=3>"

答案 1 :(得分:4)

如果您仍在使用Ruby 1.9.3,则可以非常轻松地使用Hash对象:

class Test
  attr_accessor :a, :b, :c

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

  def print()
    puts @a
    puts @b
    puts @c
  end
end

Test.new( {:a => 1, :b => 2, :c => 3}).print()
# 1
# 2
# 3
# => nil

请注意,它会创建一个名为“密钥”的变量,如果与abc不匹配,则访问者将失败。

答案 2 :(得分:3)

当前版本的Ruby中,您可以使用关键字参数:

def initialize(a: nil, b: nil, c: nil)
  @a, @b, @c = a, b, c
end

请注意,目前,关键字参数始终具有默认值,因此始终是可选的。如果你想强制使用关键字参数,你可以使用默认值任何 Ruby表达式的简单技巧:

def mand(name) raise ArgumentError, "#{name} is mandatory!" end

def initialize(a: mand 'a', b: mand 'b', c: mand 'c')
  @a, @b, @c = a, b, c
end

在Ruby的下一个版本中,可以通过省略默认值来使用强制关键字参数:

def initialize(a:, b:, c:)
  @a, @b, @c = a, b, c
end

见这里:

class Test
  def initialize(a:, b:, c:)
    @a, @b, @c = a, b, c
  end

  def to_s
    instance_variables.map {|v| "#{v} = #{instance_variable_get(v)}" }.join("\n")
  end
end

puts Test.new(a: 1, b: 2, c: 3)
# @a = 1
# @b = 2
# @c = 3
相关问题