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 her开发者_如何学Goe.
Thanks
There's a newline character at the end of your string. Use gets.chomp instead.
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]
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.
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]
加载中,请稍侯......
精彩评论