# Convert month string to number

**URL:** <https://www.ruby-forum.com/t/convert-month-string-to-number/144225>\
**Category:** Ruby\
**Created:** [July 27, 2008, 1:08am UTC](https://www.ruby-forum.com/t/convert-month-string-to-number/144225 "2008-07-27T01:08:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![adler1](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/858c86/32.png) [@adler1](https://www.ruby-forum.com/u/adler1)\
**Post date:** [July 27, 2008, 1:08am UTC](https://www.ruby-forum.com/t/convert-month-string-to-number/144225/1 "2008-07-27T01:08:59Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![adler1](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/858c86/32.png) [@adler1](https://www.ruby-forum.com/u/adler1)\
**Post date:** [July 27, 2008, 1:14am UTC](https://www.ruby-forum.com/t/convert-month-string-to-number/144225/2 "2008-07-27T01:14:39Z")

</div>

Hi –

On Sun, 27 Jul 2008, Adgar M. wrote:

> I wrote the following code:  
> when “Aug” then 8  
> ^
> 
> 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
