0

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
3
  • Hm. It can't be true. Commented Nov 2, 2014 at 15:30
  • MyModel.packs[1].reduction > 0.0? Commented Nov 2, 2014 at 15:30
  • Hi @fl00r, do you see some errors on my code about that ? Thanks Commented Nov 2, 2014 at 21:58

1 Answer 1

1

Use

MyModel.packs[1].reduction.class

In your debugging, ruby doesn't have types, almost everything is an object, including numbers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.