9

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)

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

interpolation is faster because ruby creates a unique String object, while using '+' creates a String for each operand. that's why most rubysts use interpolation.
6

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

2 Comments

the first approach is 2x slower than interpolation, the second maybe worst.
Yes, it's correct. I edited my answer to point the best approach. However, it is good to know all the possible ways for doing this, because they might be useful in other cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.