【发布时间】:2013-08-02 09:23:41
【问题描述】:
为什么我不能打印常量字符串的长度? 这是我的代码:
#!/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>'
【问题讨论】:
-
变量在 Ruby 中应该是小写的,即
name而不是Name。 -
这可能是关于如何在惯用的 ruby 中插入字符串的一个很好的课程。我确信有很多语言希望人们通过添加子字符串来构建字符串,但 ruby 绝对不是其中之一。