Reputation: 1636
I understand how Ruby's syntactic sugar lets us assign a value to a variable like this
o = ExampleClass.new
o.name = "An object"
when ExampleClass
has a method:
name=(new_name)
How does this work for a class like Hash
? How would I name my method if I want to do this?
h = MyHash.new
h[:key] = value
I am not inheriting from the Hash
class.
Upvotes: 0
Views: 254
Reputation: 13014
JacobM pretty much answered the question; but I would like to add something which I read a little back about Mutable classes.
You may find this interesting. You can define a mutable class quickly using Struct
as:
MyHash = Struct.new(:x, :y)
#This creates a new class MyHash with two instance variables x & y
my_obj = MyHash.new(3, 4)
#=> #<struct MyHash x=3, y=4>
my_obj[:x] = 10
#=> #<struct MyHash x=10, y=4>
my_obj.y = 11
#=> #<struct MyHash x=10, y=11>
This automatically makes the instance variables readable, writable and mutable by []=
You can always open the class to add some new stuff;
class MyHash
def my_method
#do stuff
end
def to_s
"MyHash(#{x}, #{y})"
end
end
Upvotes: 1
Reputation: 51062
You can just have methods
def [](key_to_retrieve)
#return corresponding value here
end
and
def []=(key_to_set, value_to_set)
#set key/value here
end
Upvotes: 4