Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Float to String error

Tags:

ruby

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)
like image 405
Michael Avatar asked Jun 18 '11 16:06

Michael


2 Answers

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.

like image 172
Dogbert Avatar answered Oct 30 '22 15:10

Dogbert


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(",")

like image 20
Amokrane Chentir Avatar answered Oct 30 '22 15:10

Amokrane Chentir