【问题标题】:Strategy for reading a tab delimited file and separating file for array with attr_reader使用 attr_reader 读取制表符分隔文件并为数组分隔文件的策略
【发布时间】:2010-10-24 20:05:36
【问题描述】:

尝试获取一个简单的 test.txt 文件并在读入后将文本和整数分开以进行数组操作。这个想法是能够使用/需要来自单独的 Person 类的 attr_accessor。 所以我可以使用 :name, :hair_color, :gender

例如,假设我们的文本文件中全部由制表符分隔,为了简短起见,我只使用了空格:

Bob red_hair 38
Joe brown_hair 39
John black_hair 40

我的班级会读到这样的内容:

 class Person
    attr_accessor :name, :hair_color, :gender


   def initialize
    @place_holder = 'test'
   end

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

到目前为止我遇到策略问题的主要文件:

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

我很确定它更容易逐行操作而不是一个文件。我不知道在那之后去哪里。我知道我需要为 :name、:hair_color、:gender 分离我的数据。抛出一些代码,以便我可以尝试一下。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    如果您让initialize 方法接受namehair_colorgender 的值,您可以这样做:

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

    如果您无法修改 initialize 方法,则需要像这样一一调用 writer 方法:

    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
    

    让initialize接受属性作为参数而不必自己设置所有变量的最简单方法是使用Struct,它将整个代码缩短为:

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

    【讨论】:

    • 我忘记了.map,呵呵!感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2017-11-25
    • 2019-12-07
    • 2012-04-01
    • 2012-12-23
    • 1970-01-01
    • 2020-11-21
    相关资源
    最近更新 更多