Real Ruby Novice with question about Date class

I’m trying to pass in variables to the date field

require ‘date’

year = 2012
month = 3
day = 7

current_date = Date.new(#{year}, #{month}, #{day})

but keep getting syntax error

If I put:

current_date = Date.new(2012,3,7)

It’s fine. Beating my head up here on something basic I think.

Any help would be extremely appreciated.

Thanks!

hi Randy,

year = 2012
month = 3
day = 7

current_date = Date.new(#{year}, #{month}, #{day})

you’re (sort of) using string interpolation in a place that you don’t
need to… try this:

current_date = Date.new(year, month, day)

you don’t need the curly braces and pound signs, just stick the
variables in there as they are. when you do want to use the braces and
pound signs, is when you want to put a variable into the middle of a
string - something like this:

puts “today’s date is #{day} / #{month} / #{year}”

notice that the curly braces and pound signs are always found within a
set of quotes… the pound-sign and brace tells the interpreter that
what’s inside the braces is a variable, and not just part of the
string…

hth -

  • j

I had thought of that initially and tried it in irb as well to test and
it (current_date = Date.new(year, month, day)) was set to blank, instead
of 2455994.

When I tried it now through my script it turned out correctly.

Thanks so much for the feedback Jake! Much appreciated.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs