Nappstir
Nappstir

Reputation: 995

Adding one to all integers in an array

I am completely unsure why this isn't working. I had it working a second ago but now I can no longer get it to function properly. Initially, I'm trying to add 1 or (num) to all integers within the array.

def my_array_modification_method!(i_want_pets, num)

    i_want_pets=["I", "want", 3, "pets", "but", "only", "have", 2 ]
    i_want_pets.map!{|i| i.is_a?(Integer) ? (i + num) : i;}

end

When I try and run this:

my_array_modification_method!(i_want_pets, 1)

I get the following error message:

undefined local variable or method `i_want_pets' for #<Context:0x0000000174e6a8>
(repl):10:in `initialize'

Upvotes: 1

Views: 118

Answers (1)

Undo
Undo

Reputation: 25697

I just ran this in the console, and I think you're misunderstanding how it works. With your current code:

def my_array_modification_method!(i_want_pets, num)

    i_want_pets=["I", "want", 3, "pets", "but", "only", "have", 2 ]
    i_want_pets.map!{|i| i.is_a?(Integer) ? (i + num) : i;}

end

my_array_modification_method!(i_want_pets, 1)

You're first defining a method my_array_modification_method, but none of the code in it has been run yet. Next, you call the method, with the arguments i_want_pets and 1. Your problem is that i_want_pets hasn't been defined yet.

I think this is what you want. Define your method like this (the following all on Ruby 2.2.1):

def my_array_modification_method!(i_want_pets, num) 
    i_want_pets.map!{|i| i.is_a?(Integer) ? (i + num) : i;}
end
 => :my_array_modification_method! 

Then make a variable later called whatever you want:

array_of_pet_things = ["I", "want", 3, "pets", "but", "only", "have", 2 ]
 => ["I", "want", 3, "pets", "but", "only", "have", 2] 

Now, you can call the method you defined with array_of_pet_things as an argument:

my_array_modification_method!(array_of_pet_things, 1)
 => ["I", "want", 4, "pets", "but", "only", "have", 3] 

Also, note that since your method uses map!, the original array array_of_pet_things will be modified:

array_of_pet_things
 => ["I", "want", 4, "pets", "but", "only", "have", 3]

Upvotes: 1

Related Questions