Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top