ruby - 打印 string.length 时出错

标签 ruby string fixnum

为什么我不能打印常量字符串的长度? 这是我的代码:

#!/usr/bin/ruby
Name = "Edgar Wallace"
name = "123456"

puts "Hello, my name is " + Name
puts "My name has " + Name.to_s.length + " characters."

我已经读过“How do I determine the length of a Fixnum in Ruby?”,但不幸的是它对我没有帮助。

尝试后,报错:

./hello.rb:7:in `+': can't convert Fixnum into String (TypeError)
          from ./hello.rb:7:in `<main>'

最佳答案

您不能连接到带有 Fixnum 的字符串:

>> "A" + 1
TypeError: can't convert Fixnum into String
    from (irb):1:in `+'
    from (irb):1
    from /usr/bin/irb:12:in `<main>'
>> "A" + 1.to_s
=> "A1"

而且,您不需要 Name.to_s,因为 Name 已经是一个 String 对象。只需 Name 就足够了。

将 Fixnum (length) 转换为字符串:

puts "My name has " + Name.length.to_s + " characters."

或者,作为替代:

puts "My name has #{Name.length} characters."

关于ruby - 打印 string.length 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18013278/

相关文章:

ruby-on-rails - Rails , 枚举角色

ruby - 在 Ruby 中,散列共享某些值的两列的最佳方法是什么?

lisp - Lisp 中的负无穷大

ruby - 我如何在 Ruby 中始终向下舍入数字?

ruby-on-rails - 如何解析服务器端(rails)中的复选框值?

Java 搜索文本并返回文本周围的多行

c# - 如何比较两个字符串数组并将匹配的值存储在另一个字符串数组中?

python - 在 appengine 中使用拉丁字符

ruby - 类型错误 : wrong argument type with Ruby &~ operator

ruby - 在构造函数中使用 splat 运算符是否有效?