ruby - 在case语句中使用include方法

时间:2011-05-22 00:03:23

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

我正在使用这样的东西:

case referer
      when (referer.include? "some_string")
        redirect_link = edit_product_path
      when (referer.include? "some_other_string")
        redirect_link = other_product_path
end

不幸的是,即使字符some_string出现在变量referer中,也会返回nil。

这是我在Ruby控制台中尝试的内容:

ruby-1.8.7-p334 :006 > jasdeep = "RAILS"
ruby-1.8.7-p334 :026 > case jasdeep
ruby-1.8.7-p334 :027?>   when (jasdeep.include? "AI")
ruby-1.8.7-p334 :028?>   puts "Hello"
ruby-1.8.7-p334 :029?> end
=> nil

任何意见都将受到赞赏。

4 个答案:

答案 0 :(得分:33)

试试这个

jasdeep = "RAILS"
case jasdeep
when /IL/
  puts "Hello"
end

答案 1 :(得分:3)

jasdeep = "RAILS"

case
  when jasdeep.include?("AI")
    puts "Hello"
end

答案 2 :(得分:1)

case true
when referer.include? "some_string"
  redirect_link = edit_product_path
when referer.include? "some_other_string"
  redirect_link = other_product_path
end

答案 3 :(得分:0)

那个nil是puts语句的返回值,而不是来自.include?。尝试从控制台分别运行以下两个语句并观察返回的值:

jasdeep.include? "AI"

puts "hello"