# Storing data from a txt file in ruby?

**URL:** <https://www.ruby-forum.com/t/storing-data-from-a-txt-file-in-ruby/138620>\
**Category:** Rails\
**Created:** [May 26, 2008, 12:06am UTC](https://www.ruby-forum.com/t/storing-data-from-a-txt-file-in-ruby/138620 "2008-05-26T00:06:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![GabrielG1976](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/8491ac/32.png) [@GabrielG1976](https://www.ruby-forum.com/u/GabrielG1976)\
**Post date:** [May 26, 2008, 12:06am UTC](https://www.ruby-forum.com/t/storing-data-from-a-txt-file-in-ruby/138620/1 "2008-05-26T00:06:49Z")

</div>

Hello Im trying to write a a ruby program that takes a list of books  
title ,author so on and i can read in the file with no problem but im  
trying to store the list into either a array or hash so i ca say run  
different methods view, delete ect…

anyhelp would be great this is what i have so far

IO.foreach(“book\_list.txt”) do |line|  
catalog=line.chomp.split(",")  
products.store(items[0].to\_i,  
[catalog[1],catalog[2].to\_i,catalog[3].to\_i)  
end

thanks for anyhelp

Gabriel

---

<div class="post-metadata">

**Author:** ![GabrielG1976](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/8491ac/32.png) [@GabrielG1976](https://www.ruby-forum.com/u/GabrielG1976)\
**Post date:** [May 26, 2008, 7:35am UTC](https://www.ruby-forum.com/t/storing-data-from-a-txt-file-in-ruby/138620/2 "2008-05-26T07:35:34Z")

</div>

GabrielG1976 wrote:

> IO.foreach(“book\_list.txt”) do |line|  
> catalog=line.chomp.split(",")  
> products.store(items[0].to\_i,  
> [catalog[1],catalog[2].to\_i,catalog[3].to\_i)  
> end

This group discusses Rails, not raw Ruby. You’d get better answers on  
the ruby  
newsgroup/mailing list/thing.

And I would just use YAML::load to read the file, and let YAML do all  
that  
low-level parsing and representing.

---

<div class="post-metadata">

**Author:** ![GabrielG1976](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/8491ac/32.png) [@GabrielG1976](https://www.ruby-forum.com/u/GabrielG1976)\
**Post date:** [May 26, 2008, 8:02am UTC](https://www.ruby-forum.com/t/storing-data-from-a-txt-file-in-ruby/138620/3 "2008-05-26T08:02:43Z")

</div>

This is how you can do it:

ar = []  
ha = {}  
IO.foreach(“book\_list.txt”) do |line|  
catalog=line.chomp.split(",")  
products.store(items[0].to\_i,  
[catalog[1],catalog[2].to\_i,catalog[3].to\_i)

# To array

ar \<\< catalog

# To Hash

ha[‘some\_key’] = catalog  
end

It can be done as oneliner:  
ar=[]  
File.readlines(“book\_list.txt”).each {|line| ar \<\<  
line.chomp.split(",")}

by  
TheR
