Kæmpe Klunker
Kæmpe Klunker

Reputation: 865

Ruby - transform initialized array to normal array with numbers?

assuming i got this input .txt

10000, 150
345, 32

When i have initialized from an input file into a class like this:

class A
    def initialize(b,c)
    @b = b
    @c = c
    end
end

input = File.open("data", "r")
input.each do |line|
    l = line.split(',')
    arr << A.new(l[0], l[1])
end

p arr

i get this output [#A:0x00000002816440 @b="10000", @c=" 150">

how can i get it to an array like this

[[10000, 150][345, 32]]

Upvotes: 0

Views: 70

Answers (3)

sawa
sawa

Reputation: 168101

Improvement suggested by Neil.

File.readlines("input.txt").map{|s| s.split(",").map(&:to_i)}
# => [[10000, 150], [345, 32]]

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118271

Assuming input.txt contains the below data :

10000, 150
500, 10
8000, 171
45, 92

I can think of as below :

class A
  def initialize(b,c)
    @b = b
    @c = c
  end
  def attrs
    instance_variables.map{|var| instance_variable_get(var).to_i}
  end
end

input = File.open('/home/kirti/Ruby/input.txt', "r")
ary = input.each_with_object([]) do |line,arr|
  l = line.split(',')
  arr << A.new(*l).attrs
end

ary
# => [[10000, 150], [500, 10], [8000, 171], [45, 92]]

Upvotes: 1

Neil Slater
Neil Slater

Reputation: 27207

I think you can do two things:

  • Convert the string inputs to numbers

  • Assuming you have further use for the class A, add a .to_a method to the class

You could do the first part in multiple places, but a simple thing to do is have the class sort out the conversion. Then the resulting code would look like this:

class A
  def initialize(b,c)
    @b = b.to_i
    @c = c.to_i
  end

  def to_a
    [ @b, @c ]
  end
end

input = File.open("data", "r")
input.each do |line|
    l = line.split(',')
    arr << A.new(l[0], l[1]).to_a
end

p arr

Upvotes: 0

Related Questions