Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiple assignment with return values in ruby (1.9) case statement?

Doing this works fine:

q = case period_group
  when 'day' then [7, 'D'] 
  when 'week' then [7, 'WW'] 
  else ['12','MM']
end
limit,pattern = q[0],q[1]

But my first try:

limit, pattern = case period_group
  when 'day' then 7, 'D' 
  when 'week' then 7, 'WW' 
  else '12','MM'
end

ends up in a SyntaxError:

syntax error, unexpected ',', expecting keyword_end
      when 'day' then 7, 'D' 

Am I missing something?

like image 761
Sjors Branderhorst Avatar asked Sep 07 '12 08:09

Sjors Branderhorst


2 Answers

You should be returning array for this. Otherwise it confuses the parser.

limit, pattern = case period_group
  when 'day' then [7, 'D'] 
  when 'week' then [7, 'WW'] 
  else ['12','MM']
end

I don't see why you wanted to get rid of square brackets. It's even more readable that way.

like image 86
Sergio Tulentsev Avatar answered Oct 25 '22 18:10

Sergio Tulentsev


you forgot to put returned values inside []

limit, pattern = case period_group
  when 'day' then [7, 'D']     
  when 'week' then [7, 'WW']     
  else ['12','MM']    
end  
like image 41
sumskyi Avatar answered Oct 25 '22 18:10

sumskyi