如何使用变量而不是预定义的名称来分配ruby的OpenStruct属性。我可以做到以下几点,
os = OpenStruct.new
os.one = 1
os.two = "Two"
但是我如何制作它以使属性名称变量? 例如:
attr_name = "sand_box"
os.#{attr_name} = "Play time!" #### this doesn't work
答案 0 :(得分:1)
require 'ostruct'
os = OpenStruct.new
os.one = 1
os.two = "Two"
attr_name = "sand_box"
os[attr_name] = "Play time!"
p os #-> #<OpenStruct one=1, two="Two", sand_box="Play time!">
答案 1 :(得分:0)
或者,您可以调用setter方法:
os.public_send(:"#{attr_name}=", 'Play time!')