0

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]]
2
  • Do you want the class A to have the string versions of the params, or is it part of exploring how to get the end result? Commented Nov 30, 2013 at 15:33
  • well i need to compare the input numbers with other numbers(int) alot of times in the rest of the code. Commented Nov 30, 2013 at 15:37

3 Answers 3

2

Improvement suggested by Neil.

File.readlines("input.txt").map{|s| s.split(",").map(&:to_i)}
# => [[10000, 150], [345, 32]]
Sign up to request clarification or add additional context in comments.

4 Comments

This is what to do if the class A is not relevant - i.e. the two-part arrays are the best representation of the data in the rest of the code. Except I'm not so sure about use of split($/) - why not just use File#each_line?
@NeilSlater Yeah, that may be better. I first wrote it where a string is given. I will rewrite it.
Somehow, File.each_line is not defined in Ruby 2.1. Maybe it has been deprecated.
I don't have 2.1 available to verify. Recall it's an instance method, so would be File.open("input.txt").each_line - so File.readlines is a better choice anyway.
1

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]]

Comments

0

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

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.