0

I can't figure out why I get this error message when I run my file on the console: no block given (yield) (LocalJumpError)

Here my code:

def block_splitter(array)
  array.partition { |item| yield(item) }
end

beatles = ["John", "Paul", "Ringo", "George"]

puts block_splitter(beatles) do |beatle|
  beatle.start_with?("P")
end

Thanks for your help!

raphael-allard
  • 205
  • 2
  • 9

2 Answers2

1

So there is a problem with missing parentheses. Ruby interpreter allow not to use those, but when You use nested method calls It's better (and sometimes necessary) to use them. To fix it You can do something like this

    puts(block_splitter(beatles) do |beatle| 
        beatle.start_with?("P")
    end)

Or even better

puts(block_splitter(beatles) {|beatle| beatle.start_with?("P")})
1

It's a whitespace issue. Your problem is in this line:

puts block_splitter(beatles) do |beatle|
  # ...
end

The above code is being interpreted like this:

puts(block_splitter(beatles)) do |beatle|
  # ...
end

I.e. the ruby interpreter thinks that the block is being passed to the puts method, not the block_splitter method.

By assigning a variable and printing the result, you'll see that this works as expected:

result = block_splitter(beatles) do |beatle|
  beatle.start_with?("P")
end

puts result

Or, you can define this as a 1-liner, and the ruby interpreter handles it like you expected:

puts block_splitter(beatles) { |beatle| beatle.start_with?("P") }

Or, you could wrap it in extra brackets:

puts(block_splitter(beatles) do |beatle|
  beatle.start_with?("P")
end)
Tom Lord
  • 27,404
  • 4
  • 50
  • 77