# How do you make a hash key using a wordy string?

**URL:** <https://www.ruby-forum.com/t/how-do-you-make-a-hash-key-using-a-wordy-string/154748>\
**Category:** Ruby\
**Created:** [December 3, 2008, 3:15pm UTC](https://www.ruby-forum.com/t/how-do-you-make-a-hash-key-using-a-wordy-string/154748 "2008-12-03T15:15:24Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mmcolli00](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/85e7bf/32.png) [@mmcolli00](https://www.ruby-forum.com/u/mmcolli00)\
**Post date:** [December 3, 2008, 3:15pm UTC](https://www.ruby-forum.com/t/how-do-you-make-a-hash-key-using-a-wordy-string/154748/1 "2008-12-03T15:15:24Z")

</div>

Hello everyone.

How do you make a hash key using a string? For instance,

txt file…  
1 This is a string 22234343  
2 This is another string 434355455  
3 This is a different string 34324545

file = File.open(“mytext4hash.txt”)  
file.each\_line do |line|  
rows = {}  
key, val = line.chomp.split("""",4)  
rows[key] = val

#this is where I am having issue.  
puts rows[“1 This is a string”] #need this to point to only “22234343”

end

Thanks in advance. MC

---

<div class="post-metadata">

**Author:** ![mmcolli00](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/85e7bf/32.png) [@mmcolli00](https://www.ruby-forum.com/u/mmcolli00)\
**Post date:** [December 3, 2008, 4:27pm UTC](https://www.ruby-forum.com/t/how-do-you-make-a-hash-key-using-a-wordy-string/154748/2 "2008-12-03T16:27:22Z")

</div>

Try this:

file = File.open(“mytext4hash.txt”)  
rows = {}  
file.each\_line do |line|  
/(.+)\s+(\d+)$/ =~ line.chomp  
key = Regexp.last\_match(1)  
val = Regexp.last\_match(2)  
rows[key] = val  
end  
puts rows[“1 This is a string”] #need this to point to only “22234343”

First, you were initializing “rows” inside the loop, which meant you  
only kept the last line parsed! The regular expression does this:

(.+) matches at least one character (defaults to starting at the  
beginning) and save it in the first “capture group”. The parentheses  
do that for you. I then refer to it on the next line; the “1” passed  
to last\_match.  
\s+ matches at least one space.  
(\d+)$ matches at least one digit at the end of the line ($) and  
saves it as the second capture group.

Make sense?

dean

---

<div class="post-metadata">

**Author:** ![mmcolli00](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/85e7bf/32.png) [@mmcolli00](https://www.ruby-forum.com/u/mmcolli00)\
**Post date:** [December 3, 2008, 10:40pm UTC](https://www.ruby-forum.com/t/how-do-you-make-a-hash-key-using-a-wordy-string/154748/3 "2008-12-03T22:40:12Z")

</div>

Thanks Dean. Makes sense!
