views:

77

answers:

1

we have made the following code and trying to run it.

class Numeric
def gram 
self
end
alias_method :grams, :gram

def of(name)
    ingredient = Ingredient.new(name)
    ingredient.quantity=self
    return ingredient
  end
end


class Ingredient 
      def initialize(n)
        @@name= n
        end

      def quantity=(o)
      @@quantity = o
       return @@quantity
     end

     def name
       return @@name
     end

     def quantity
       return @@quantity
     end

   end

e= 42.grams.of("Test")
a= Ingredient.new("Testjio")
puts e.quantity
a.quantity=90
puts a.quantity
puts e.quantity

the problem which we are facing in it is that the output of

puts a.quantity
puts e.quantity

is same even when the objects are different. what we observed is that second object i.e 'a' is replacing the value of the first object i.e. 'e'. the output is coming out to be

42
90
90

but the output required is

42
90
42

can anyone suggest why is it happening? it is not replacing the object as object id's are different..only the values of the objects are replaced.

+2  A: 

The problem is that you're using the class variable @@quantity instead of the instance variable @quantity. There's only one of the class Ingredient, so that variable is shared across the instances. Just remove the extra @ sign and it'll be behave as you expect; there's one @quantity per instance of Ingredient.

See http://www.techotopia.com/index.php/Ruby_Variable_Scope#Ruby_Class_Variables

Edit: Here's a more succinct version of Ingredient that saves you having to write the accessors.

class Ingredient
  attr_accessor :quantity, :name

  def initialize(n)
    @name = n
  end
end
Isaac Cambron
Also, if you're using accesors for quantity and name instance variables, you can just define `attr_accessor :quantity` and `attr_reader :name` and omit the methods at all.
Chubas
True, edited to reflect that.
Isaac Cambron
oh..thank you so much..we did not notice it..it is just that we have just started with ruby.
intern
BTW: `attr_accessor`, `attr_reader` and `attr_writer` can take more than one symbol as an argument. You don't have to repeat `attr_accessor` multiple times.
Jörg W Mittag
That's a style preference I have left over from c#, but I have noticed it's idiomatic ruby to put them all on the same line.
Isaac Cambron