-5

I am new in ruby on rails. I am migrating from php to ruby. Now I have some php projects which are being converted into ruby code.But How can I convert this switch code to ruby on rails 4? function ajax($command) {

    switch ($command) {
        case 'page_reload':
            $this->ajax_delete_entries_of_current_uid();
            break;

        case 'labchem_products':
            $this->ajax_labchem_products();
            break;

        case 'labchem_carts':
            $this->ajax_labchem_carts();
            break;

        case 'labchem_customers':
            $this->ajax_labchem_customers();
            break;

        case 'products_selected':
            $this->ajax_products_selected();
            break;

        case 'products_total':
            $this->ajax_products_total();
            break;

        case 'products_delivery_info':
            $this->ajax_products_delivery_info();
            break;

        case 'labchem_orders':
            $this->ajax_labchem_orders();
            break;

        default: break;
    }
} 
HM Tanbir
  • 990
  • 12
  • 30
  • 1
    Possible duplicate of [How can I write a switch statement in Ruby?](http://stackoverflow.com/questions/948135/how-can-i-write-a-switch-statement-in-ruby) – jmargolisvt Feb 13 '16 at 15:42
  • the best way is to lern ruby before trying to port something to ruby. the easiest way is to pay someone who knows ruby. the worst way is asking on SO, obviously before putting "ruby switch case" in the search engine of your choice – Franz Gleichmann Feb 13 '16 at 15:56

1 Answers1

2
case command
  when 'page_reload'      then ajax_delete_entries_of_current_uid()
  when 'labchem_products' then ajax_labchem_products()
  # or
  when 'labchem_carts'
    ajax_labchem_carts()
  # and so on ...
end

You don't need break. Only one or no when will be executes. If no when matches you could note an else to execute something.

In ruby the case will return the last value, so you could save it to a variable.

result =
  case command
    when 'a', 'b' then 1
    when 'c' then 2
    when 'd'..'z' then 3
    else
      0
  end

The comparison is done by object type and value (===).

case 1
  when '1' then 'a'
  when 1 then 'b'
end
# => "b"

More at ruby-doc.com and tutorialspoint.com.

guitarman
  • 3,290
  • 1
  • 17
  • 27
  • I'd try and avoid using `then` as much as possible, it increases readability having the "action" part of the `when` broken out into a separate line, especially when the clause is pretty long. Good examples here, though! – tadman Feb 13 '16 at 17:37