Jstuff
Jstuff

Reputation: 1344

Is self not equal to the instance variable?

Learning Ruby here and this is my first endeavor into OOP and below is my complete code which makes a hash class. I'm having trouble understanding what is happening behind the scenes in the union method. When I change self.to_a.each { |key| joined_set.insert(key) } to @store.to_a.each { |key| joined_set.insert(key) } the hash joined_set becomes an array of arrays containing the keys and values of @store while it just contains the keys if I use just self and not @store. How does this discrepancy arise? Is self not equal to the instance variable?

class MyHashSet
  def initialize
   @store = {}
  end

 def insert(el)
   @store[el] = true
 end

 def include?(el)
    return true if @store[el]
 false
 end

 def delete(el)
    if @store[el]
      @store.delete(el)
      return true
    else
      return false
    end
   end

  def to_a
    @store.keys
  end

  def union(set2)
     joined_set = self.class.new
     self.to_a.each { |key| joined_set.insert(key) }
     set2.to_a.each { |key| joined_set.insert(key) }
     joined_set
   end

 end

Upvotes: 0

Views: 149

Answers (2)

philomory
philomory

Reputation: 1767

The more specific reason you're getting different results is that self.to_a is equal to @store.keys. Why? because that's how you defined to_a:

def to_a
  @store.keys
end

@store.keys and @store.to_a are very different from each other; @store is a ruby Hash, and Hash#to_a returns an array of arrays, with each subarray being a key-value pair, like [[key1, value1], [key2, value2]]; Hash#keys, on the other hand, just returns an array of keys.

Upvotes: 1

borbesaur
borbesaur

Reputation: 691

self is not equal to the instance variable.
self is equal to the current object, which, in this case, would be the current instance of the MyHashSet class.
so @store is an attribute of self in this case.

if you had an attr_accessor for @store, then @store would be equal to self.store

Upvotes: 0

Related Questions