Welcome to the list of Frequently Asked Questions on the ruby-talk mailing list ! Feel free to add to it!
What are the ruby-talk best practices/guidelines?
How do I convert a ruby script into a distributable executable?
What is the best Ruby GUI framework?
What is the best editor for Ruby?
Ruby should do X!
Why does ruby’s comparison with floats fail?
here is a list comparing some
Instructions on how to submit a patch
Sometimes floats in Ruby do funky things.
Example of odd behavior:
>> (2.0-1.1) == 0.9 => false
Why? Because floats are by default slightly imprecise
This is not Ruby’s fault, but floating point numbers in general suffer from this type of rounding error, because they’re limited to x number of bytes, and, in general, cannot store decimal number perfectly.
>> 1.1 => 1.1 > 0.9 => 0.9 > 1.1-0.9 => 0.20000000000000007
Your options when you run into this:
assert_in_delta((1.1-0.9), 0.2, 0.0001) # passes
>> require 'bigdecimal' >> (BigDecimal.new("1.1") - BigDecimal.new("0.9")) == 0.2 => true
>> Rational(11, 10) - Rational(9, 10) # 11/10 - 9/10 => (1/5) >> Rational(11, 10) - Rational(9, 10) == 0.2 => true
How can I make them pretty again, in 1.9.2+ ?
class Float def pretty_s num = "%.12f" % self num =~ /\..*?(0+)$/ num.sub!($1, '') # might be like 2. at this point num = num[0..-2] if num[-1] == '.' num end end p 1.1-0.9 # >> 0.20000000000000007 p (1.1-0.9).pretty_s >> "0.2" p 2.0.pretty_s >> "2"
With 1.9.0 and 1.9.1, gem uses “gem_prelude” to load files from gems. This sped things up quite a bit for startup time, but introduced a few subtle bugs with rubygems so was basically set to be used far less in 1.9.2. It basically loaded the “lib” paths of each highest numbered gem to the require path.
In 1.9.2, if you ever do a
require 'rubygems' it reverts back to the normal “full” rubygems. In 1.9.1 it reverts to “full” rubygems if you ever use a gem specific constant or method, like
In 1.9.1, if you want to avoid using the somewhat buggy gem_prelude, then run your script like
ruby --disable-gems script_name.rb and include the
require 'rubygems' line in your script, or upgrade to 1.9.2
Note: this is not the first ruby faq. Take a step back in history and see the original
Last edited by dlchet,