How to put elements of a file into a hash? -Ruby
hash[key] = value
to add a new key-value pair. hash.update(otherhash)
to add the key-value-pairs from otherhash to hash.
If you do hash = foo
, you reassign hash, losing the old contents.
So for your case, you can do:
hash = {}
File.open(file_path) do |fp|
fp.each do |line|
key, value = line.chomp.split("\t")
hash[key] = value
end
end
Read file into hash with 2 values per key?
I suppose this is the expected result:
File.readlines('/tmp/blah.cfg').map do |line|
line.split(',', 2).map(&:strip)
end.to_h
#⇒ {"server1"=>"jim, 22", "server2"=>"bob, 44"}
One might also split the rest into an array:
File.readlines('/tmp/blah.cfg').map do |line|
k, *v = line.split(',').map(&:strip)
[k, v]
end.to_h
#⇒ {"server1"=>["jim", "22"], "server2"=>["bob", "44"]}
Read file into hash with 2 values per key?
I suppose this is the expected result:
File.readlines('/tmp/blah.cfg').map do |line|
line.split(',', 2).map(&:strip)
end.to_h
#⇒ {"server1"=>"jim, 22", "server2"=>"bob, 44"}
One might also split the rest into an array:
File.readlines('/tmp/blah.cfg').map do |line|
k, *v = line.split(',').map(&:strip)
[k, v]
end.to_h
#⇒ {"server1"=>["jim", "22"], "server2"=>["bob", "44"]}
How to return a hash containing an array of file names for each owner name?
Here you want to iterate over the file hash and for each key value pair you need to check if it already exists in your new hash, then you just want to add the file name to the array or you create a new key value pair.
def change_hash(file_hash)
new_hash = {}
file_hash.each do |file_name, person|
if new_hash[person]
new_hash[person] << file_name
else
new_hash[person] = [file_name]
end
end
new_hash
end
If you struggle with this, you want to look on how you can manipulate hashes (and arrays) in Ruby. Let me know if you have any more questions.
Reading text file, parsing it, and storing it into a hash. How?
No reason for anything this simple to look ugly!
h = {}
lines.each_with_index do |line, i|
quantity, item, price = line.match(/^(\d+) (.*) at (\d+\.\d+)$/).captures
h[i+1] = {quantity: quantity.to_i, item: item, price: price.to_f}
end
Parsing a .txt file to key/value pairs in Ruby
You can do
array = []
# open the file in read mode. With block version you don'r need to
# worry about to close the file by hand. It will be closed when the
# read operation will be completed.
File.open('path/to/file', 'r') do |file|
# each_line gives an Enumerator object. On which I'm calling
# each_slice to take 2 lines at a time, where first line is the
# question, and the second one is the answer.
file.each_line.each_slice(2).do |question, answer|
array << {'Question' => question, 'Answer' => answer}
end
end
Get key value pair of hash for the given key , in ruby
There is a method, Hash#assoc can do similar things. But it returns the key and value in an array, which you can easily change it into a hash.
And an alternative is use Hash#select, which does return a hash according to the block given.
h1 = { "fish" => "aquatic animal", "tiger" => "big cat" }
h1.assoc "fish" # ["fish", "aquatic animal"]
h1.select { |k,v| k == "fish" } # {"fish"=>"aquatic animal"}
Related Topics
Pg Error Could Not Connect to Server: Connection Refused Is the Server Running on Port 5432
Are Ruby 1.9 Regular Expressions Equally Powerful to a Context Free Grammar
"Errno::Eaccess...Permission Denied" Running Compass Watch
Retrieve Contents of Url as String
Rails 5 Actioncontroller::Invalidauthenticitytoken Error
Change Error Field Name in Rails
Ruby: No Such File or Directory @ Rb_Sysopen - Testfile (Errno::Enoent)
Understanding Ruby Symbol as Method Call
Why Doesn't This Work If in Ruby Everything Is an Object
Ruby Create Recursive Directory Tree
How to Load Some Activerecord Models from a Yaml File and Save Them to the Db
Carrierwave - Resizing Images to Fixed Width
"Don't Run Bundler as Root" - What Is the Exact Difference Made by Using Root