intern
intern

Reputation: 141

fluent interface program in Ruby

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.

Upvotes: 1

Views: 683

Answers (1)

user24359
user24359

Reputation:

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

Upvotes: 3

Related Questions