Convert month string to number

A

Adgar Marks

Hi all,

I use linux OS. I would like to convert a file with the folloing format:
-rw-r--r-- 1 student student 11289 26. Jul 22:41 listing.txt

into FileName, Year, Month, Day

In order to do this, i would like to convert the month string from "Jul"
in to the number 7.

I wrote the following code:

def ConvertMonthToNumber(MonthStr)
case MonthStr
when "Jan" then 1
when "Feb" then 2
when "Mar" then 3
when "Apr" then 4
when "May" then 5
when "Jun" then 6
when "Jul" then 7
when "Aug" then 8
when "Sep" then 9
when "Okt" then 10
when "Nov" then 11
when "Dec" then 12
end
end

when i run this code, i get the following error:
SortList.rb:7: formal argument cannot be a constant
def ConvertMonthToNumber(MonthStr)
^

My questions are:
1. Is there already a function that does in Ruby?
2. How to correct this bug?

Thanks
 
D

David A. Black

Hi --

Hi all,

I use linux OS. I would like to convert a file with the folloing format:
-rw-r--r-- 1 student student 11289 26. Jul 22:41 listing.txt

into FileName, Year, Month, Day

In order to do this, i would like to convert the month string from "Jul"
in to the number 7.

I wrote the following code:

def ConvertMonthToNumber(MonthStr)
case MonthStr
when "Jan" then 1
when "Feb" then 2
when "Mar" then 3
when "Apr" then 4
when "May" then 5
when "Jun" then 6
when "Jul" then 7
when "Aug" then 8
when "Sep" then 9
when "Okt" then 10
when "Nov" then 11
when "Dec" then 12
end
end

when i run this code, i get the following error:
SortList.rb:7: formal argument cannot be a constant
def ConvertMonthToNumber(MonthStr)
^

My questions are:
1. Is there already a function that does in Ruby?
2. How to correct this bug?

1. require 'date'
Date::ABBR_MONTHNAMES.index("Jun") # 6

2. Use a variable instead of a constant as your parameter. Variables
start with lowercase letters or _ (underscore).


David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top