aldanux aldanux - 5 months ago 7
Ruby Question

Ruby - How to change an instance variable in various objects using map method

Lets have a class like this:

class Foo
attr_accessor :var_1, :var_2, :var_3

def initialize(var_1, var_2, var_3)
@var_1 = var_1
@var_2 = var_2
@var_3 = var_3
end
end


and now we create some objects:

a = Foo.new("c", 1, "d")
b = Foo.new("e", 2, "f")
c = Foo.new("g", 3, "h")


then we make an array with the new created objects:

array = [a, b, c]


And here where I'm stuck, I want to add a new value to an specific instance variable from object.

Example:

I try to change
var_2
increased by one, but I don't know how to call or assign it to the instance variable
var_2
:

newArray = array.map { |x|

x.var_1 + 1 # assign the new value to the instance variable 'var_2'
}

def showArray(array)

array.each do | var |
puts "Var 1: #{var.var_1} | Var 2: #{var.var_2} | Var 3: #{var.var_3}"
end
end

showArray(newArray)

# desired output:
# => Var 1: c | Var 2: 2 | Var 3: d
# => Var 1: e | Var 2: 3 | Var 3: f
# => Var 1: g | Var 2: 4 | Var 3: h


I have to use the map method.

Answer

The issue you have is that your map function is returning the value of x.var_1 + 1 which is an Integer. When you loop back over it, you're looping over Integers not Foo objects.

You almost have it, you just need to use an assignment operator such as +=to assign val_2 to itself + 1 like this:

newArray = array.map { |x|
   x.var_2 += 1 
   x
}

def showArray(array)

  array.each do | var |
    puts "Var 1: #{var.var_1} | Var 2: #{var.var_2} | Var 3: #{var.var_3}"
  end
end

showArray(newArray)

output:

Var 1: c | Var 2: 2 | Var 3: d
Var 1: e | Var 2: 3 | Var 3: f
Var 1: g | Var 2: 4 | Var 3: h
Comments