简体   繁体   中英

Ruby: Reading Lines from File Splitting them into Struct

I have a text file that I want to read which is line separated in this format "Item1", 1 "Item2", 34 "Item3", 6 etc.

I want to input each part of the line into a new instance of my Struct. What syntax should I use to accomplish this? I'm hitting a mental wall.

Item = Struct.new(:name, :price)
File.readlines('MASTER_INVENTORY.txt').map do |line|
  Item.new << line.split
end
Item = Struct.new(:name, :price)
File.readlines('MASTER_INVENTORY.txt').map do |line|
  line.scan(/"(.*?)",\s*(\S*)/).map do |item, price|
    Item.new(item, price.to_i)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM