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
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