0

I receive the following hash:

my_hash = {a:(1/20), b:(1/26)}

But when I see the hash I get the following:

irb(main):019:0> my_hash = {a:(1/20), b:(1/26)}
=> {:a=>0, :b=>0}
irb(main):020:0> my_hash
=> {:a=>0, :b=>0}

As you can see it convert to Integer (0)

How can I leave as Rational, or float so I can sort my_hash.sort_by {|key, value| value}?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Felipe Maion
  • 336
  • 1
  • 12

2 Answers2

2

The syntax for a Rational literal in Ruby is <numerator>/<denominator>r, e.g. 1/2r or 23/42r. What you have is just integer division: 1 divided by 20 is 0.

my_hash = { a: 1/20r, b: 1/26r }
#=> { :a => (1/20), :b => (1/26) }

It looks like you might be a Smalltalk or Scheme programmer, but in those languages the situation is different: they had rational literals from the beginning, Ruby only got them later, and so it needs an explicit annotation (the r suffix) to tell rational literals apart from just integer division; otherwise you would break existing programs.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • I would do this (.to_r) or r if I was defining the hash, but I receive the hash, and when I try to sort I got all wrong. – Felipe Maion May 14 '17 at 01:44
  • Jorg, I've never coded in Smaltalk or Scheme. I am having this trouble trying to solve one problem at Codewars. – Felipe Maion May 14 '17 at 02:41
1

Define as such:

my_hash = {a:(1.0/20.0), b:(1.0/26.0)}

Or alternatively:

my_hash = {a:(1.to_f/20.to_f), b:(1.to_f/26.to_f)}
E Rullmann
  • 344
  • 3
  • 12