#between? error or anomaly in Cooper * Start of Ruby *

Cooper's book, “Getting Ruby” on page 166 has an example that I cannot reproduce.

class Song include Comparable attr_accessor :length def <=>(other) @length <=> other.length end def initialize(song_name, length) @song_name = song_name @length = length end end a = Song.new('Rock around the clock', 143) b = Song.new('Bohemian Rhapsody', 544) c = Song.new('Minute Waltz', 60) a.between?(b, c) 

The book says that the result should be => true , while I get => false .

I kept breaking it into ...

 puts 143.between?(544, 60) # => false puts 143.between?(60, 544) # => true 

And according to ruby-doc.org, it should be written as between?(min,max) - which makes me believe

  • a) the book has an error.
  • b) in an earlier version of Ruby, between? was more flexible and acceptable (max,min)
  • c) this example is somehow abnormal and I'm missing something

What is it?

+5
source share
3 answers

This was discussed in some of the comments above, but as the author of the book, I wanted to clarify that the 2009 edition (edition 2) of the book fixed this problem. The original poster updated that they read the 2007 edition :-)

As a final answer to the question, however, yes, the first edition of the book was erroneous.

+2
source

After a quick investigation, this just looks like a mistake in the book (if you quote it correctly).

I found the book as pdf here . Sorry, page 166 is missing. However, page 5 says:

In the "Ruby on Windows" section, you will see several links for different versions of Ruby that you can download for Windows. Ideally, you want to download the file at the highest link in the list called the “one-click installer”. At the time of this writing, this version is 1.8.5.

Checking CRuby 1.8.5 Comparable implementation , you can clearly see what is between? works like today.

+4
source

I just wanted to show you this. Is this the C source for the between? method between? :

  static VALUE cmp_between(VALUE x, VALUE min, VALUE max) { if (RTEST(cmp_lt(x, min))) return Qfalse; if (RTEST(cmp_gt(x, max))) return Qfalse; return Qtrue; } 

Until I reviewed each version, I believe that this method has not changed since Ruby 1.8.7.

cmp_lt and cmp_gt in plain English: "compare less" and "compare more".

So, as you can see, the method will return false if the value of x , which in your case is your length a length 144, is less than min , which will be b length 544. Since 144 <544, you get the correct answer, and it seems that the book contains an error.

It seems that I can’t determine if this error has ever been before, so if you are prone, it may be useful to contact the author and let him know.

+2
source

Source: https://habr.com/ru/post/1236976/


All Articles