Ruby newbie. What's wrong with this code?
city_details['longitude'] + "," + city_details['latitude']
I get this error:
./player_location.rb:6:in `+': String can't be coerced into Float (TypeError)
It looks like city_details['longitude']
and city_details['latitude']
are Float
values.
You cannot add Float
to a String
in Ruby like this. You can either convert everything to String
, and then +
them, or use String interpolation.
city_details['longitude'].to_s + "," + city_details['latitude'].to_s
"#{city_details['longitude']},#{city_details['latitude']}"
Most Rubyists tend to use String interpolation.
It complains about the fact that you are trying to concatenate a float
with a string
.
The better way of doing this is by doing String interpolation:
"#{city_details['longitude']}, #{city_details['latitude']}"
Other possible solutions:
You could convert each float to string, by calling the to_s
method like this:
city_details['longitude'].to_s + "," + city_details['latitude'].to_s
Or you could use the join
method:
[city_details['longitude'], city_details['latitude']].join(",")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With