Ruby float 到字符串错误

标签 ruby

Ruby 新手。这段代码有什么问题?

city_details['longitude'] + "," + city_details['latitude']

我收到这个错误:

./player_location.rb:6:in `+': String can't be coerced into Float (TypeError)

最佳答案

看起来 city_details['longitude']city_details['latitude']Float 值。

您不能像这样在 Ruby 中将 Float 添加到 String。您可以将所有内容转换为 String,然后 + 它们,或者使用 String 插值。

city_details['longitude'].to_s + "," + city_details['latitude'].to_s

"#{city_details['longitude']},#{city_details['latitude']}"

大多数 Rubyist 倾向于使用字符串插值。

关于Ruby float 到字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6397204/

相关文章:

mysql - rails 5.1 : Primary Key is not a BIGINT

ruby - 选择上一个 td 并单击与 Mechanize 和 Nokogiri 的链接

ruby-on-rails - 在firefox中网站被重定向到 "https"(其他浏览器正常)

ruby-on-rails - 如何修复“致命的 :unable to look up https (port 9418) (No such host is known)

ruby-on-rails - 我无法让 git 忽略我的 Ruby on Rails 项目的 tmp 文件夹

javascript - 编译后的文件没有获得指纹轨

Ruby - 如何将 EOF 标记添加到 PDF 文件中或以其他方式绕过 PDF::Reader::MalformedPDFError: PDF 不包含 EOF 标记

ruby - 识别 Treetop 语法中的 Ruby 代码

ruby-on-rails - Rails 从对象创建路由

ruby - 验证框架的替代 Rails