user1594138
user1594138

Reputation: 1011

Replacing manually written date with a string containing it

I have these 2 things I am working with:

CSV.foreach('datafile.csv','r') {|row| D_Location << row[0]}

puts Date.new(2003,05,02).cwday

In the first line I would like to change the datafile.csv to something like a string so I can change one string and it changes for all of these codes. I have many, each controlling 1 csv column.

In the second one I would like to replace the actual date written, and replace it with a string. This is so that can be automatic, because the string will be generated based on other criteria.

I trust the mods will ban me if I'm being too much of a noob hehe. Then I'll toughen up and find these answers myself eventually. But so far I've solved a lot, but not this. Thanks in advance!

Upvotes: 3

Views: 91

Answers (2)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

For the first part of your question, you're already working with a string. I think what you mean is that you want it to be in a variable:

csv_file = 'datafile.csv'
CSV.foreach(csv_file,'r') {|row| D_Location << row[0]}

For the second part of your question, Date.parse() works with strings, but they need to be in a format that it can recognize. If your date strings use commas, you can replace them with hyphens:

date_str = "2003,05,02"
Date.parse(date_str.gsub(",", "-")).cwday # => 5

It's not clear where your date strings will be coming from or what format they'll be in, but the general concepts you need to understand are that you can use variables, and that you can transform strings.

Upvotes: 1

Prof. Falken
Prof. Falken

Reputation: 24887

Make a function which takes in a string representing a weekday, and returns a number. Call this function later in your code:

Date.new(2003, 05, yourfun('Tuesday')).cwday

Upvotes: 1

Related Questions