【问题标题】:How to convert this php code to ruby (RoR) code? [closed]如何将此 php 代码转换为 ruby​​ (RoR) 代码? [关闭]
【发布时间】:2016-02-13 15:39:14
【问题描述】:

我是 ruby​​ on rails 的新手。我正在从 php 迁移到 ruby​​。现在我有一些 php 项目正在被转换为 ruby​​ 代码。但是我怎样才能将这个开关代码转换为 rails 4 上的 ruby​​? 函数 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;
    }
} 

【问题讨论】:

  • 最好的方法是在尝试将某些东西移植到 ruby​​ 之前学习 ruby​​。最简单的方法是付钱给懂红宝石的人。最糟糕的方法是询问 SO,显然是在将“ruby switch case”放入您选择的搜索引擎之前

标签: php ruby-on-rails ruby switch-statement


【解决方案1】:
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

您不需要break。只有一个或没有when 将被执行。如果没有 when 匹配,您可以记下 else 来执行某些操作。

在 ruby​​ 中,case 将返回最后一个值,因此您可以将其保存到变量中。

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

按对象类型和值 (===) 进行比较。

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

更多信息请访问ruby-doc.com 和 tutorialspoint.com。

【讨论】:

  • 我会尽量避免使用then,它将when 的“动作”部分分成单独的行来增加可读性,尤其是当子句很漂亮时长。不过,这里有很好的例子!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 2013-06-28
  • 2023-03-09
  • 2012-11-21
  • 1970-01-01
  • 2011-05-06
  • 2018-05-06
相关资源
最近更新 更多