Hash and function parameters in ruby -
i'd write :
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
is there way instanciate object , map parameters hash table?
thanks in advance.
class test def initialize(options) options.each |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
or use openstruct
:
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ostruct/rdoc/openstruct.html
here's simple example:
require 'ostruct' puts openstruct.new(:a => 1, :b => 2, :c => 3).inspect # outputs: "#<openstruct a=1, b=2, c=3>"
Comments
Post a Comment