Domanda

Copying this code from book Programming Ruby and running it in rubyfiddle.com . Getting syntax error instead of # => 21​ ? Any help is appreciated!

arr = [ 1, 1, 2, 3, 5, 8, 13, 21, 34 ]
res = arr.bsearch ​do​ |val|
  ​case​
​    ​when​ val < 19 ​then​ +1
​   ​when​ val > 23 ​then​ -1
​   ​else​ 0
​  end​  ​  
​end​
​   
res ​# => 21​
È stato utile?

Soluzione

Having tested your code myself, there is nothing wrong with what you have written. In all likelihood you (or in this case, codecademy) are using an older version of Ruby. The bsearch method was defined on Array and Range in Ruby 2.0. Prior to Ruby 2.0, there were several gems that could be used to perform a binary search on an array.

To test which version of Ruby you are using, type the following into irb or your codecademy console:

> RUBY_VERSION
=> "2.1.1" 

If the number returned is less than "2.0", bsearch will not be natively defined for either Array or Range

Altri suggerimenti

As you specified in one of your comment the exact error is:

(eval):48: undefined method `bsearch' for [1, 1, 2, 3, 5, 8, 13, 21, 34]:Array (NoMethodError)

This error means the method bsearch doesn't exist for Array.


In labs.codecademy.com

 > RUBY_VERSION
=> "1.8.7"

There is no bsearch in Ruby 1.8.7.
bsearch has been implemented in Ruby 2.0.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top