John
John

Reputation: 4706

Fixnum String conversion

I want to get a string of the current time in Ruby:

"Time is " + Time.new.month + "/" + Time.new.day + "/" + Time.new.year

But it says "can't convert Fixnum into String". How can I fix this?

Upvotes: 2

Views: 243

Answers (4)

christianblais
christianblais

Reputation: 2458

Whenever possible, prefer string interpolation over concatenation. As you can clearly see in that (thread), using string interpolation would have automatically called to_s for you.

Using string interpolation :

"Time is #{Time.new.month}/#{Time.new.day}/#{Time.new.year}"

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230296

Or you could just use right tool for the job: time formatting.

Time.new.strftime "Time is %m/%d/%Y" # => "Time is 11/13/2012"

Upvotes: 4

tadman
tadman

Reputation: 211560

Ruby can only add string to string, so conversion is required. As a note, elements interpolated in double-quoted strings are automatically converted:

now = Time.new
"Time is #{now.month}/#{now.day}/#{now.year}"

It's also possible to combine them from an array where they are also automatically converted:

now = Time.new
"Time is " + [ now.month, now.day, now.year ].join('/')

You can also use sprintf-style interpolation:

now = Time.new
"Time is %d/%d/%d" % [ now.month, now.day, now.year ]

The second one gives you more control over formatting. For example %02d will pad with 0 to two places.

As Sergio points out, there's a special-purpose function for this formatting that is probably a better idea. Also Time.now is the traditional method for now, whereas Time.new is for creating arbitrary times.

Upvotes: 3

Koen.
Koen.

Reputation: 26939

You could use to_s

"Time is " + Time.new.month.to_s + "/" + Time.new.day.to_s + "/" + Time.new.year.to_s

But event better is to use strftime

Time.new.strftime("Time is %-m/%e/%Y")

Upvotes: 3

Related Questions