Łukasz Korol Łukasz Korol - 6 months ago 14
Ruby Question

Translating date to day of week

I have a method to translate naming days of week to my native language:

def translate_date(daytime)
case daytime
when daytime.strftime('%A') == 'Monday'
'Poniedziałek'
when daytime.strftime('%A') == 'Tuesday'
'Wtorek'
when daytime.strftime('%A') == 'Wednesday'
'Środa'
when daytime.strftime('%A') == 'Thursday'
'Czwartek'
when daytime.strftime('%A') == 'Friday'
'Piątek'
when daytime.strftime('%A') == 'Saturday'
'Sobota'
when daytime.strftime('%A') == 'Sunday'
'Niedziela'
end
end


I use it for example as:

date = Sat, 21 May 2016 00:00:00 UTC +00:00
translate_date(date) # => nil


Where is the problem with this method? Why does it return
nil
?

Meanwhile, I get:

date.strftime('%A') == 'Saturday' # => true`

Answer

Checking the expression after case with the expression after when happens like this:

daytime === (daytime.strftime('%A') == 'Monday')
# => nil

The problem is that you are trying to compare daytime after case with nil after when. So, if all when return nil, all expression returns nil.

Use case statement correctly:

def translate_date(daytime)
  case daytime.strftime('%A')
  when 'Monday'
    'Poniedziałek'
  when'Tuesday'
    'Wtorek'
  when 'Wednesday'
    'Środa'
  when 'Thursday'
    'Czwartek'
  when 'Friday'
     'Piątek'
  when 'Saturday'
    'Sobota'
  when 'Sunday'
    'Niedziela'
  end
end
date = Date.parse("Sat, 21 May 2016 00:00:00 UTC +00:00")
# => Sat, 21 May 2016
translate_date(date)
# => "Sobota"

Also, as @AnthonyE mentioned in comments, it is better to use internationalization for your goal.