How Ruby Treats Hash Like an Instance

Asked 2 years ago, Updated 2 years ago, 28 views

I don't know if the title is appropriate, but

class Hoge
  def fuga
    {:piyo=>1}
  end
end

If there is a class like this, I think it will be used as follows.

 hoge=Hoge.new
hoge.fuga[:piyo]#=>1

What is the best way to do it if you want to be able to see it in hoge.fuga.piyo as well?
If the number is small and the key is fixed, I think it can be a method or instance variable, but
Is it possible to implement it so that even if the contents of the hash (including the key) change dynamically?

Thank you for your cooperation.

ruby

2022-09-29 21:57

1 Answers

How about OpenStruct (require'ostruct')?


2022-09-29 21:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.