开发者

Strategy for reading a tab delimited file and separating file for array with attr_reader

开发者 https://www.devze.com 2023-01-21 13:46 出处:网络
Trying to take a simple test.txt file and separate the text and integers after its read in for array manipulation. The idea is to be able to use/require the attr_accessor from the separate Person clas

Trying to take a simple test.txt file and separate the text and integers after its read in for array manipulation. The idea is to be able to use/require the attr_accessor from the separate Person class. So I can use :name, :hair_color, :gender

For example lets says we have in our text file which is all separated by the tab delimiter, for shortness I just used space:

Bob red_hair 38
Joe brown_hair 39
John black_hair 40

My class would read something like:

 class Person
    attr_accessor :name, :hair_color, :gender


   def initialize
    @place_holder = 'test'
   end

   def to_s
    @test_string = 'test a string'
   end
 end

My main file that I'm having strategy issues with so far:

 test_my_array = File.readlines('test.txt').each('\t')  #having trouble with 

I'm pretty sure its easier to manipulate line by line rather then one file. I'm not sure where to go after that. I know I need to separate my data some how for :n开发者_StackOverflowame, :hair_color, :gender. Throw some code up so I can try things out.


If you make your initialize method accept values for name, hair_color and gender, you can do it like this:

my_array = File.readlines('test.txt').map do |line|
  Person.new( *line.split("\t") )
end

If you can't modify your initialize method, you'll need to call the writer methods one by one like this:

my_array = File.readlines('test.txt').map do |line|
  name, hair_color, gender = line.split("\t")
  person = Person.new
  person.name = name
  person.hair_color = hair_color
  person.gender = gender
  person
end

The easiest way to make initialize accept the attributes as argument without having to set all the variables yourself, is to use Struct, which shortens your entire code to:

Person = Struct.new(:name, :hair_color, :gender)
my_array = File.readlines('test.txt').map do |line|
  Person.new( *line.split("\t") )
end
#=> [ #<struct Person name="Bob", hair_color="red_hair", gender="male\n">,
#     #<struct Person name="Joe", hair_color="brown_hair", gender="male\n">,
#     #<struct Person name="John", hair_color="black_hair", gender="male\n">,
#     #<struct Person name="\n", hair_color=nil, gender=nil>]
0

精彩评论

暂无评论...
验证码 换一张
取 消