0

So I was just playing with blocks in ruby, and I wrote this code:

#!/usr/bin/env ruby

def my_map ary
    a = ary.clone
    if block_given?
        while element = a.shift
            yield element
        end
    else
        ary
    end
end

array = [1, 2, 3, 4, 5]

my_map array { |e|
    puts e * 2
}

p array

But it keeps giving me this error:

./tests.rb:16:in `<main>': undefined method `array' for main:Object (NoMethodError)

Why is that? I can clearly see that I defined array. I would appreciate any help, thanks!

3 Answers 3

2

The Ruby interpreter parses:

my_map array { |e|
    puts e * 2
}

as:

my_map(array ( { |e| puts e * 2 } ) ) 

which explains, why it thinks array should be a method, to avoid that change:

my_map array { |e|
    puts e * 2
}

to:

my_map(array) { |e|
    puts e * 2
}

or:

my_map array do |e|
    puts e * 2
end

the curly braces are meant for one-liner blocks and should be avoided for multi-line blocks

Sign up to request clarification or add additional context in comments.

3 Comments

Since { is used for both hashes and blocks, the parser can get tripped up if it doesn't know which one to expect.
@tadman it does not expect a hash, as an hash there would come as an argument which does not occur without a comma
Ah, right, it's parsing as my_map(array { |e| ... }) vs. the expected my_map(array) { |e| ... }. I tend to use brackets pretty rigorously to avoid this ambiguity.
0

When passing an argument and a multi-line block, you have to put the argument between braces

my_map(array) { |e|
  puts e * 2
}

or use a do end block

my_map array do |e|
  puts e * 2
end

Anyway this one-line block looks the best approach for this case:

my_map(array) { |e| puts e * 2 }

1 Comment

the one-liner would fail if the params is not in parens
0

this should work:

my_map(array) { |e|
    puts e * 2
}

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.