Hi, just a beginners question,
This is my program:
module Foo
class Bar
def initialize()
arr = [1,2,3,4,5]
arr.collect! { |n| n * -1 }
end
end
end
Now I’ve read that I also can use this (do they call it private ?)
method:
class Array
def multiply_by(x)
collect { |n| n * x }
end
end
and use it later on, like this:
module Foo
class Bar
def initialize()
arr = [1,2,3,4,5]
#arr.collect! { |n| n * -1 }
arr.multiply_by(5) # multiply each member of the array by 5
end
end
end
This does not work, how do i fit the method in my module?
Thnx!
Hi,
I assume you mean “@arr = [1,2,3,4,5]” rather than “arr = [1,2,3,4,5]”.
Because “arr = …” creates a local variable that would simply be
discarded in this case.
Your code doesn’t work because you use “collect” in your “multiply_by”
method instead of “collect!”. When you call “multiply_by”, the array
won’t change. Instead, you get a new array with the multiplied numbers:
ar = [1, 2]
new_ar = ar.multiply_by 4
p ar # still the same: [1, 2]
p new_ar # the new array returned by the method: [4, 8]
To correct your code, you can either change the definition of “multiply
by” to
def multiply_by x
collect! {|n| n * x}
end
or change the initialize method to something like this:
def initialize()
apply the method to the array [1,2,3,4,5] and store the resulting
array [5,10,15,20,25] in the instance variable @arr
@arr = [1,2,3,4,5].multiply_by 5
end
By the way: This has nothing to do with private methods. A private
method is a method that can only be called from within the object
(roughly speaking).
Jacques