简体   繁体   中英

Iterating over a multidimensional array?

class Lod

attr_accessor :lodnr
attr_accessor :lobnr
attr_accessor :stknr

def initialize(lodnr, lobnr, stknr)
    @lodnr = lodnr
    @lobnr = lobnr
    @stknr = stknr.chomp
end

def to_s
    "%8s, %5s, %3s" % [@lodnr, @lobnr, @stknr]
end
end

I have an array called sold which contains these four arrays:

[10000, 150, 5]
[500, 10, 1]
[8000, 171, 3]
[45, 92, 4]

The four arrays are objects of a class, imported from at .txt file.

    input = File.open("lodsedler.txt", "r")
input.each do |line|
    l = line.split(',')
    if l[0].to_i.between?(0, 99999) && l[1].to_i.between?(1, 180) && l[2].to_i.between?(1, 10)
        sold << Lod.new(l[0], l[1], l[2])
    else
        next
    end
end

I want to count the first value in each array, looking for a randomly selected number which is stored in first .

The error I get is always something like this, whatever i try:

Undefined method xxx for #Lod:0x0000000022e2d48> (NoMethodError)

The problem is that i can't seem to acces the first value in all the arrays.

You could try

a = [[10000, 150, 5], [500, 10, 1],[8000, 171, 3],[45, 92, 4]]

You can access a[0][0] 10000 or a[2][1] 171 or iterate

a.each do |row|
  row.each do |column|
      puts column  
  end
end

Edit for comment regarding using braces instead of do:

Sure it's possible but I believe do..end in preferred: https://stackoverflow.com/a/5587403/514463

a.each { |row|
  row.each { |column|
      puts column  
  }
}

An easy way to get the first element of each sub array is to use transpose:

special_number = 45
array = [
  [10000, 150, 5],
  [500, 10, 1],
  [8000, 171, 3],
  [45, 92, 4]
]

p array.transpose.first.count(special_number) #=> 1

Edit: Actually simpler and more direct...

p array.map(&:first).count(special_number) #=> 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM