For some reason the hash I created doesn't return the value when I try to get argument from the command line.
Here's the code
DIAL_BOOK = {
"East Bay": 510,
"San Francisco": 415,
"San Jose": 650,
}
city = gets.chomp
if city == "East Bay"
puts "Area Code: #{DIAL_BOOK[city]}
end
Output Results
Which area code would you like to find out
East Bay
Area Code:
I'm completely confused on what's going on here. When I hard code "East Bay" to the hash it returns me 510 just fine. Anybody have an suggestion on what's going on?
:city
, instead of the actual variable city
. #
and not a $
(eg #{DIAL_BOOK[city]}
). city
contains a string. Either change your hash to use strings as keys ( DIAL_BOOK = { 'Easy Bay' => 510 }
) or convert the city to a symbol before lookup ( #{DIAL_BOOK[city.to_sym]
). Additionally, you may want to simplify and remove your if
condition unless you specifically only want to print the value for "East Bay".
The variable city
is different from symbol :city
. To interpolate string in ruby use
#{expression}
inside a double quotes because double quotes allow for escape sequences while single quotes do not.
city = gets.chomp
puts "Area Code: #{DIAL_BOOK[city]}" if city == "East Bay"
For strings as keys in hash, use rocket =>
instead of :
. Otherwise you will have to use city.to_sym
instead of city
.
DIAL_BOOK = {
"East Bay" => 510,
"San Francisco" => 415,
"San Jose" => 650,
}
The rocket operator can take in any literal that aren't valid labels. A :
assumes a valid label on its left. DIAL_BOOK[:'East Bay'] #=> 510
{ :$set => 11 } # Valid
{ $set: 11 } # Invalid
{ :'where.is.pancakes.house?' => 23 } # Valid
{ 'where.is.pancakes.house?': 23 } # Invalid
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.