Undefined method 'array' for main:Object

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!

Answers


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 }

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


this should work:

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

Need Your Help

C Array passed to a function: how to absolutely prevent it from being written?

c arrays pointers const

I would like to prevent an array of integer passed to a function from being altered : use of const

c# BsonSerializer: deserialization through backing fields

c# .net mongodb serialization mongodb-.net-driver

I'm starting to work with MongoDB using official c# driver. The problem is that I can't find a way to make bsonseriazer use fields (not properties) for setting the deserialized data and at the same...