我有一系列符号:
main_row = [:b, :r, :g, :o]
和另一个数组cells
,其中填充了Cell
class:
class Cell
attr_accessor :colour
def initialize(colour = nil)
@colour = colour
end
end
cells = [Cell.new(:b), Cell.new(:g), Cell.new(:r), Cell.new(:o)]
我需要计算cells
中main_row
中的元素与correct
中具有相同索引的元素具有相同颜色的数量,并将它们存储在名为correct # => 2
的变量中。
Date
答案 0 :(得分:3)
Cell = Struct.new(:colour)
cells = [Cell.new(:b), Cell.new(:g), Cell.new(:r), Cell.new(:o)]
main_row = [:b, :r, :g, :o]
correct = cells.zip(main_row).count { |cell, colour| cell.colour == colour }
#=> 2
答案 1 :(得分:2)
Cell = Struct.new(:colour)
cells = [Cell.new(:b), Cell.new(:g), Cell.new(:r), Cell.new(:o)]
main_row = [:b, :r, :g, :o].each
cells.count{|c| c.colour == main_row.next } # => 2
答案 2 :(得分:2)
main_row.each_index.count { |i| main_row[i] == cells[i].colour }
#=> 2
答案 3 :(得分:1)
cells = [Cell.new(:b), Cell.new(:g), Cell.new(:r), Cell.new(:o)]
main_row = [:b, :r, :g, :o]
cells.select.with_index { |c, i| i == main_row.index(c.colour) }.size
#=>2
答案 4 :(得分:1)
cells = [Cell.new(:b), Cell.new(:g), Cell.new(:r), Cell.new(:o)]
main_row = [:b, :r, :g, :o]
cells.map.with_index{ |c, i| i == main_row.index(c.colour) }.count(true)
#=> 2