Sanju
Sanju

Reputation: 80

Hash problem in Ruby

I am newbie in Ruby.. seeking some help..

I have a code

DB = { 'key1' => "value1",
       'key2' => "value2"}

key = gets
DB["#{key}"]

when i enter key1 from console i get nil how to resolve this?

I tried few different alternative but could not solve it. hope to get help here.

Thanks

Upvotes: 1

Views: 251

Answers (4)

Linuxios
Linuxios

Reputation: 35783

Ruby's gets returns the value from the console including the newline character (\n). In practice, unless you need a newline to be on your input, get input with var=gest.chomp. chomp is a method of String the removes ending \n, \r, and \r\n characters. So your code would be this:

key=gets.chomp
puts DB[key]

Upvotes: 0

ase
ase

Reputation: 13461

What are you trying to do? It is not completely clear in your question.

If you want to access the value in DB by entering the key I would do it like this:

DB = { 'key1' => "value1", 'key2' => "value2"}
key = gets.strip
puts DB[key]

Upvotes: 1

Andy Gaskell
Andy Gaskell

Reputation: 31761

There's a newline character at the end of your string. Use gets.chomp instead.

Upvotes: 6

Carl Smotricz
Carl Smotricz

Reputation: 67750

Well, "key1" is just a string, like "value1".

If you want to pull "value1" out of DB using "key1", then all you need is

DB["key1"]

which will give you your "value1" back.

Upvotes: 0

Related Questions