Reputation: 3272
I don't know if it's "normal" but whenever I want to use my variables in statements I need to convert them into integer/float even if I declare them as integer/float. Am I doing something wrong or is it just the way that Ruby works ? Thanks
For example, my declarations :
Struct.new("Pack", :id, :qty, :promo, :reduction)
@@pack1 = Struct::Pack.new(1, 10, 0, 0.1)
@@pack2 = Struct::Pack.new(2, 25, 0, 0.1)
@@pack3 = Struct::Pack.new(3, 50, 5, 0.1)
@@pack4 = Struct::Pack.new(4, 100, 10, 0.1)
def self.packs
[0, @@pack1, @@pack2, @@pack3, @@pack4]
end
Let's take reduction
for this example. When I use them it is not recognize as float even if I declare them as 0.1 without " "
. Doesn't enter in IF statement:
def my_function(pack_id)
reduction = MyModel.packs[pack_id].reduction
Rails.logger.debug reduction # Print 0.1
if reduction > 0.0
# Some stuff
end
end
IF statement is working :
def my_function(pack_id)
reduction = MyModel.packs[pack_id].reduction.to_f
Rails.logger.debug reduction # Print 0.1
if reduction > 0.0
# Some stuff
end
end
For information :
2.1.3 :001 > MyModel.packs
=> [0, #<struct Struct::Pack id=1, qty=10, promo=0, reduction=0.1>, #<struct Struct::Pack id=2, qty=25, promo=0, reduction=0.1>, #<struct Struct::Pack id=3, qty=50, promo=5, reduction=0.1>, #<struct Struct::Pack id=4, qty=100, promo=10, reduction=0.1>]
2.1.3 :002 > MyModel.packs[1].reduction
=> 0.1
2.1.3 :003 > MyModel.packs[1].reduction.type
NoMethodError: undefined method `type' for 0.1:Float
EDIT :
The main difference seams here, I can't explain why right now. When my application is running :
Rails.logger.debug MyModel.packs[1].reduction.class # Fixnum
In rails console :
2.1.3 :012 > MyModel.packs[1].reduction.class
=> Float
Upvotes: 0
Views: 288
Reputation: 6075
Use
MyModel.packs[1].reduction.class
In your debugging, ruby doesn't have types, almost everything is an object, including numbers.
Upvotes: 1