S
S
Stan_12015-05-13 08:38:30
Ruby on Rails
Stan_1, 2015-05-13 08:38:30

How to "rewrite" the square bracket method in Ruby?

Good afternoon!
I can't find it with a search, I don't know if it's possible. Please help. Let's say I'm writing my own class, and I have a Hash variable in it. Something like this

class MyClass
   def initialize
      @hash = Hash.new
   end
end

And now I want to do this:
my = MyClass.new
my[:section] = Hash.new
my[:section][:subsection] = 10
puts my[:section][:subsection]

How do I properly overwrite square brackets to access a multilevel hash?
The simplest seems to be inheritance from Hash. But I still need to do some transformations inside the hash. That is, I would like to make my own method. Or accept such a request in method_missing and parse it there?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Vsk, 2015-05-13
@viktorvsk

In what you wrote - your class has nothing to do with it.
Redefine brackets - no problem.

class MyClass
  def self.[](var)
  end

  def [](var)
  end
end

But in the case shown, you want to munch the embedded hash.
In this case, not MyClass is needed, but MyHash, which will inherit Hash. Here he is and change the brackets

A
Anton Radushevsky, 2015-05-16
@doromones

I think something like this
I usually use the construction

h = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }

h['bar'] -> {}
h['tar']['star']['par'] -> {}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question