-2

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​
alk
  • 69,737
  • 10
  • 105
  • 255
user3222947
  • 197
  • 1
  • 2
  • 14

2 Answers2

2

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

wvandaal
  • 4,265
  • 2
  • 16
  • 27
  • @JörgWMittag yes it does, if you read the OP's comments, the error was `undefined method 'bsearch' for [1, 1, 2, 3, 5, 8, 13, 21, 34]:Array(NoMethodError)` – wvandaal May 06 '14 at 21:11
0

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.

Micka
  • 1,648
  • 1
  • 19
  • 34
  • The exact error, as specified in one of the comment by @user3222947 is `(eval):48: undefined method 'bsearch' for [1, 1, 2, 3, 5, 8, 13, 21, 34]:Array (NoMethodError)` – Micka May 07 '14 at 08:23
  • @JörgWMittag, I added the specified error in my answer. – Micka May 07 '14 at 08:30
  • That's not a syntax error (`SyntaxError`), that's a semantic error (`NoMethodError`). The OP mentioned three times that he is getting a syntax error as well, *that's* what I am puzzled by. The `NoMethodError` is obvious. – Jörg W Mittag May 07 '14 at 08:33
  • @JörgWMittag, You have it. The `syntax error` in the question only means `error`. Then the error should have been specified as well in the question but is only written in the comment section. There are many misleading mistakes here. – Micka May 07 '14 at 08:38