2

I'm trying to pass an array and a block to a function but am getting the following errors:

./rb:7: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
test( [0,1,2,3], {puts 'string'} )
                    ^
./rb:7: syntax error, unexpected '}', expecting end-of-input
test( [0,1,2,3], {puts 'string'} )

Code in question:

1 #!/usr/bin/env ruby
2 
3 def test(arr, &b)
4   b.call
5 end
6 
7 test( [0,1,2,3], {puts 'string'} )

2 Answers 2

4

The block shouldn't be passed as a parameter to the method 'test'.

The following will work:

test([0,1,2,3]) {puts 'string'}

Alternatively, you can create a proc (which is an object unlike a block) and pass it to the 'test' method.

p = Proc.new {puts 'string'}
test([0,1,2,3], &p)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I'll accept this when I can, it seems counter-intuitive to be able to have a block as a parameter in a function, but then not be able to have it as an argument when you call the function.
You can also do test [0,1,2,3] do puts 'string' end if you don't want to use parenthesis.
0

Methods can accept either unnamed/unassigned block in form method(args) {unnamed block} or assigned to proc/lambda/whatever passed as a normal argument in form method(args, &object), where an ampersand symbol means an argument is attempted to convert to Proc with #to_proc method.

test([0,1,2,3], &->{puts 'string'})   # lambda
test([0,1,2,3], &MyClass.new)         # MyClass should implement to_proc

class MyClass
  def to_proc
    puts 'string'
  end
end

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.