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

21

我正在使用类似于这样的东西:

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 Console中尝试的内容:

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个回答

39

试试这个

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

1
在“when”布尔值中使用变量是否可行? - Nick
1
@Nick 可以这样写: puts "variable" end``` - Maxim Krizhanovsky
什么是IL? - Unkas
1
@Unkas,它是作为正则表达式的一部分进行测试的字符串(在jasdeep =“RAILS”中使用/IL/)。 - MrVocabulary

3
jasdeep = "RAILS"

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

谢谢Nash,但是那没有帮助到我。 - Jasdeep Singh

0

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

jasdeep.include? "AI"

puts "hello"

ruby-1.8.7-p334 :040 > puts "hello" hello => nil - Jasdeep Singh

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

1
这会导致在Ruby 1.9.3(以及我想象中的后续版本)中出现“语法错误”。 - aceofbassgreg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接