2

Why can't I print the length of a constant string? This is my code:

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

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

I've already read "How do I determine the length of a Fixnum in Ruby?", but unfortunately it didn't help me.

After trying, this error is thrown:

./hello.rb:7:in `+': can't convert Fixnum into String (TypeError)
          from ./hello.rb:7:in `<main>'
Community
  • 1
  • 1
blah
  • 65
  • 7
  • 2
    Variables should be lowercase in Ruby, i.e. `name` instead of `Name`. – Stefan Aug 02 '13 at 09:56
  • This might be a good lesson on how to interpolate strings in idiomatic ruby. I'm sure there a lot of languages where people are expected to build strings by adding substrings but ruby is definitely not one of them. – Justin L. Aug 02 '13 at 11:23

2 Answers2

12

You cannot concatenate to a String with a 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"

And, you don't need Name.to_s, because Name is already a String object. Just Name is enough.

Convert the Fixnum (length) to String:

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

Or, as an alternative:

puts "My name has #{Name.length} characters."
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
falsetru
  • 357,413
  • 63
  • 732
  • 636
2

Use interpolation "#{}" in Ruby. It will evaluate your expression and print your string:

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

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

Note: You can not use interpolation if you are using a string with single quotes('). Use it with double quotes.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
rohitkadam19
  • 1,734
  • 5
  • 21
  • 39