我想写这样的东西:

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

是否有方法实例化一个对象并用哈希表映射其参数?
提前谢谢。

最佳答案

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>"

关于ruby-on-rails - ruby 中的哈希和函数参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18109440/

10-13 02:17