Sjors Branderhorst
Sjors Branderhorst

Reputation: 2182

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?

Upvotes: 10

Views: 9860

Answers (2)

sumskyi
sumskyi

Reputation: 1835

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  

Upvotes: 3

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

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.

Upvotes: 23

Related Questions