优雅链接'或'用于测试Ruby中的相同变量

sno*_*gel 5 ruby

什么是明智的说法.

if @thing == "01" or "02" or "03" or "04" or "05"
Run Code Online (Sandbox Code Playgroud)

(这些数字包含在数据类型字符串列中.)

Mic*_*ski 11

制作一个数组并使用 .include?

if ["01","02","03","04","05"].include?(@thing)
Run Code Online (Sandbox Code Playgroud)

如果值确实都是连续的,您可以使用类似(1..5).include? For strings 的范围,您可以使用:

if ("01".."05").include?(@thing)
Run Code Online (Sandbox Code Playgroud)

  • @MДΓΓБДLL:Ruby有设置,所以`Set.new("01".."05").include?`将是`O(1)`. (5认同)