Answer the question
In order to leave comments, you need to log in
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
my = MyClass.new
my[:section] = Hash.new
my[:section][:subsection] = 10
puts my[:section][:subsection]
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question