0

I have array

numbers = [ 1, 2, 3, 4, 5, 6 ]

I have a variable:

number = 4

I want with a loop for or each block return false unless the number 4 for this case exist in array.

numbers.each do |number_loop| 
    return false unless number_loop == number   
end

But I get an error:

LocalJumpError: unexpected return from (irb):25:in `block in irb_binding'

2
  • Is this code obfuscated for the purposes of posting here? Because there are far better ways to determine if an array contains a value. Commented Feb 7, 2012 at 19:34
  • What do you think you're returning from? Commented Feb 7, 2012 at 19:40

3 Answers 3

1

Unless you're doing something else in the block that you've hidden from posting here, why don't you just do:

return false if numbers.include? number

As for the reason you get a LocalJumpError there: if your code isn't in a method then there isn't anything to return to (or, put another way: nothing to jump back to). In that case you're probably trying to set a variable rather than return, and you'd want to do:

is_included = numbers.include? number
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you it does works fine. This response its perfect. Thank you
0

Try with :

 numbers.include?(number)

It should work.

Comments

0

As others have mentioned you should use #include? to check for inclusion. Also take a look at #any? and #all? which can be used to check whether any or all elements in a collection match a certain block.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.