2013-09-12 3 views
0

Как можно обработать массив @test_array целых чисел, создавая новый массив @cells, который содержит экземпляр класса Cell для каждого элемента массива, поставив значение @test_array элемента в переменную экземпляра @value вновь созданного объекта?Изменение переменных объекта в массиве переменных экземпляра в Ruby,

Впоследствии, я хочу иметь возможность изменять @value различных объектов, а в конце программы я хочу вывести массив из всех объектов @value.

class Cells 

    attr_accessor :value 

    def initialize(value) 
    @value = value 
    end 

end 

class Grid 

    attr_accessor :test_array, :cells 

    def initialize 
    @test_array = [1, 2, 3, 4] 
    @cells = [] 
    @test_array.each { |value| @cells << Cell.new(value) } 
    end 

    def put_values_of_objects_to_array 
    @cells.value_to_a ???????? 
    end 

end 

Это то, что я получаю после выполнения кода, принимая во внимание один из ответов:

2.0.0p247 :080 > cells = [] 
=> [] 
2.0.0p247 :081 > abc = [1,2,3,4,5,6,7,8,9] 
=> [1, 2, 3, 4, 5, 6, 7, 8, 9] 
2.0.0p247 :082 > abc.map {|value| cells << Cell.new(value)} 
=> [[#<Cell:0x007fe3dc3313d8 @value=1>, #<Cell:0x007fe3dc3313b0 @value=2>, #<Cell:0x007fe3dc331388 @value=3>, #<Cell:0x007fe3dc331360 @value=4>, #<Cell:0x007fe3dc331338 @value=5>, #<Cell:0x007fe3dc331310 @value=6>, #<Cell:0x007fe3dc3312e8 @value=7>, #<Cell:0x007fe3dc3312c0 @value=8>, #<Cell:0x007fe3dc331298 @value=9>], [#<Cell:0x007fe3dc3313d8 @value=1>, #<Cell:0x007fe3dc3313b0 @value=2>, #<Cell:0x007fe3dc331388 @value=3>, #<Cell:0x007fe3dc331360 @value=4>, #<Cell:0x007fe3dc331338 @value=5>, #<Cell:0x007fe3dc331310 @value=6>, #<Cell:0x007fe3dc3312e8 @value=7>, #<Cell:0x007fe3dc3312c0 @value=8>, #<Cell:0x007fe3dc331298 @value=9>], [#<Cell:0x007fe3dc3313d8 @value=1>, #<Cell:0x007fe3dc3313b0 @value=2>, #<Cell:0x007fe3dc331388 @value=3>, #<Cell:0x007fe3dc331360 @value=4>, #<Cell:0x007fe3dc331338 @value=5>, #<Cell:0x007fe3dc331310 @value=6>, #<Cell:0x007fe3dc3312e8 @value=7>, #<Cell:0x007fe3dc3312c0 @value=8>, #<Cell:0x007fe3dc331298 @value=9>], [#<Cell:0x007fe3dc3313d8 @value=1>, #<Cell:0x007fe3dc3313b0 @value=2>, #<Cell:0x007fe3dc331388 @value=3>, #<Cell:0x007fe3dc331360 @value=4>, #<Cell:0x007fe3dc331338 @value=5>, #<Cell:0x007fe3dc331310 @value=6>, #<Cell:0x007fe3dc3312e8 @value=7>, #<Cell:0x007fe3dc3312c0 @value=8>, #<Cell:0x007fe3dc331298 @value=9>], [#<Cell:0x007fe3dc3313d8 @value=1>, #<Cell:0x007fe3dc3313b0 @value=2>, #<Cell:0x007fe3dc331388 @value=3>, #<Cell:0x007fe3dc331360 @value=4>, #<Cell:0x007fe3dc331338 @value=5>, #<Cell:0x007fe3dc331310 @value=6>, #<Cell:0x007fe3dc3312e8 @value=7>, #<Cell:0x007fe3dc3312c0 @value=8>, #<Cell:0x007fe3dc331298 @value=9>], [#<Cell:0x007fe3dc3313d8 @value=1>, #<Cell:0x007fe3dc3313b0 @value=2>, #<Cell:0x007fe3dc331388 @value=3>, #<Cell:0x007fe3dc331360 @value=4>, #<Cell:0x007fe3dc331338 @value=5>, #<Cell:0x007fe3dc331310 @value=6>, #<Cell:0x007fe3dc3312e8 @value=7>, #<Cell:0x007fe3dc3312c0 @value=8>, #<Cell:0x007fe3dc331298 @value=9>], [#<Cell:0x007fe3dc3313d8 @value=1>, #<Cell:0x007fe3dc3313b0 @value=2>, #<Cell:0x007fe3dc331388 @value=3>, #<Cell:0x007fe3dc331360 @value=4>, #<Cell:0x007fe3dc331338 @value=5>, #<Cell:0x007fe3dc331310 @value=6>, #<Cell:0x007fe3dc3312e8 @value=7>, #<Cell:0x007fe3dc3312c0 @value=8>, #<Cell:0x007fe3dc331298 @value=9>], [#<Cell:0x007fe3dc3313d8 @value=1>, #<Cell:0x007fe3dc3313b0 @value=2>, #<Cell:0x007fe3dc331388 @value=3>, #<Cell:0x007fe3dc331360 @value=4>, #<Cell:0x007fe3dc331338 @value=5>, #<Cell:0x007fe3dc331310 @value=6>, #<Cell:0x007fe3dc3312e8 @value=7>, #<Cell:0x007fe3dc3312c0 @value=8>, #<Cell:0x007fe3dc331298 @value=9>], [#<Cell:0x007fe3dc3313d8 @value=1>, #<Cell:0x007fe3dc3313b0 @value=2>, #<Cell:0x007fe3dc331388 @value=3>, #<Cell:0x007fe3dc331360 @value=4>, #<Cell:0x007fe3dc331338 @value=5>, #<Cell:0x007fe3dc331310 @value=6>, #<Cell:0x007fe3dc3312e8 @value=7>, #<Cell:0x007fe3dc3312c0 @value=8>, #<Cell:0x007fe3dc331298 @value=9>]] 
2.0.0p247 :083 > cells 
=> [#<Cell:0x007fe3dc3313d8 @value=1>, #<Cell:0x007fe3dc3313b0 @value=2>, #<Cell:0x007fe3dc331388 @value=3>, #<Cell:0x007fe3dc331360 @value=4>, #<Cell:0x007fe3dc331338 @value=5>, #<Cell:0x007fe3dc331310 @value=6>, #<Cell:0x007fe3dc3312e8 @value=7>, #<Cell:0x007fe3dc3312c0 @value=8>, #<Cell:0x007fe3dc331298 @value=9>] 
2.0.0p247 :084 > 
+0

В любом случае 'test_array.each {| значение | @cells << Cell.new (значение)} 'должно быть '@test_array.each {| значение | @cells << Cell.new (значение)} '. – steenslag

ответ

0
class Cell 
    attr_accessor :values 

    @arrs = [] #Creates a "class instance variable" 

    class <<self #Creates an accessor for the "class instance variable" 
    attr_reader :arrs 
    end 

    def initialize(values) 
    @values = values 
    self.class.arrs << @values #Add the @values array to the "class instance variable" 
    end 
end 

test_array = [1, 2, 3] 

@cells = test_array.map do |num| #Create the cells 
    Cell.new(test_array.dup) 
end 

p @cells 

--output:-- 
[#<Cell:0x0000010085ffd8 @values=[1, 2, 3]>, #<Cell:0x0000010085ff88 @values=[1, 2, 3]>, #<Cell:0x0000010085ff60 @values=[1, 2, 3]>] 


@cells.each_with_index do |cell, i| #Change the last value of each cell's @values array 
    cell.values[-1] = i 
end 


p Cell.arrs #Show all the @values arrays of all the cells: 

--output:-- 
[[1, 2, 3, 0], [1, 2, 3, 1], [1, 2, 3, 2]] 

Теперь, когда вы добавили класс сетки к вашему сообщению, вы можете добавить переменная экземпляра класса в класс Grid - а не в класс Cell - для отслеживания массивов.

class Grid 
    attr_accessor :cells 

    TEST_ARRAY = [1, 2, 3, 4] 

    @arrs = [] 
    class <<self 
    attr_reader :arrs 
    end 

    def initialize 
    @cells = [] 

    TEST_ARRAY.each do |value| 
     new_cell = Cell.new(TEST_ARRAY.dup) 
     @cells << new_cell 
     self.class.arrs << new_cell.values 
    end 

    end 

end 

эй, спасибо за это, однако, что я хочу, это один из элементов test_array идти в объект, а не весь массив.

Это не то, что это означает:

... положить значение @test_array элемента в переменный экземпляр @value

class Cell 
    attr_accessor :values 

    def initialize(value) 
    @values = [value] 
    end 
end 

class Grid 
    attr_accessor :cells 

    TEST_ARRAY = [1, 2, 3, 4] 

    @cell_values = [] 
    class <<self 
    attr_reader :cell_values 
    end 

    def initialize 
    @cells = [] 

    TEST_ARRAY.each_with_index do |value, i| 
     new_cell = Cell.new(TEST_ARRAY[i]) 
     @cells << new_cell 
     self.class.cell_values << new_cell.values 
    end 

    end 

end 

mygrid = Grid.new 
p Grid.cell_values 

mygrid.cells.each do |cell| 
    cell.values << 5 
end 

p Grid.cell_values 


--output:-- 
[[1], [2], [3], [4]] 
[[1, 5], [2, 5], [3, 5], [4, 5]] 
+0

эй, спасибо за это, однако я хочу, чтобы один элемент test_array заходил в объект, а не весь массив. –

+0

@PauloGaspar, см. Добавленный код. – 7stud

0

Это полезное упражнение и вы очень близки. Материал с объявлением массива (@cells = []), а затем перебирает другой массив, чтобы что-то делать с каждым элементом, и добавление результата в новый массив действительно работает, но это шаблон, который настолько распространен, что многие языки имеют более легкое решение. В Ruby это называется 'map' aliased as 'collect'. Демонстрация:

class Cell 

attr_accessor :value 

    def initialize(value) 
    @value = value 
    end 

end 

class Grid 

attr_accessor :test_array, :cells 

    def initialize 
    @test_array = [1,2,3,4] 
    @cells = @test_array.map{|a_value| Cell.new(a_value)} 
    end 

    def put_values_of_objects_to_array 
    @cells.map{|cell| cell.value} 
    end 

end 


f = Grid.new 
p f.put_values_of_objects_to_array #=> [1, 2, 3, 4] 
+0

Благодарим вас за этот ответ. Однако я не знаю, почему, когда я запускаю команду, он возвращает массив с 81 элементом с 81 элементом внутри каждого. Таким образом, в основном он получает объекты класса 6561. Любая идея почему? Я проверил синтаксис снова и снова, и это точно так же, как вы опубликовали ... –

Смежные вопросы