I have a file that has a name/value pair on each line, I want to open the file, read each line and initialize a hash.
file:
john, 234
joe, 2222
And load a hash so I can loop through the key value pairs.
Convert the key from a string to a symbol, and do a lookup in the hash. Rails uses this class called HashWithIndifferentAccess that proves to be very useful in such cases.
Ruby hash creation. A hash can be created in two basic ways: with the new keyword or with the hash literal. The first script creates a hash and adds two key-value pairs into the hash object. A hash object is created.
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.
Hash[*File.read('f.txt').split(/[, \n]+/)]
f = <<EOF
john, 234
joe, 2222
EOF
p Hash[*f.split(/, |\n/)]
The method #split gives an array looking like ["john,", "234", "joe,", "2222"]. The * (AKA splat) operator converts this array to a bunch of arguments. Hash#[] takes this bunch of arguments (when there are an even number of arguments) and delivers a hash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With