tags:

views:

72

answers:

4

Hi, 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

A: 

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.

Carl Smotricz
Ooh, most of us misunderstood the problem. Andy got it right. You're not getting the right value because the result from gets is not exactly "key1".
Carl Smotricz
+6  A: 

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

Andy Gaskell
and you can just use DB[key] instead of DB["#{key}"]
Aurélien Bottazzini
Thanks:-) it works
Sanju
+1  A: 

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]
adamse
A: 

I agree with Andy. gets.chomp should work

Shiv