0
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.

2
  • 4
    Where does this Lod class come into the picture? Your description says these are arrays, not Lod objects. Are the numbers actually meant to be Lod objects or what? Commented Nov 26, 2013 at 1:23
  • Sorry, yes the inner arrays are Lod objects imported from text 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 Commented Nov 26, 2013 at 11:38

2 Answers 2

6

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  
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

is there any way to print that using .each loop and blocks without using do keyword. Something like a.each { |one_dimention| one_dimention.each { |number| puts number } }
Please consider updating your answer if the above is possible. Thanks.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.