Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
更高效的ruby if案例_Ruby_If Statement_Conditional - Fatal编程技术网

更高效的ruby if案例

更高效的ruby if案例,ruby,if-statement,conditional,Ruby,If Statement,Conditional,我想知道最好的方法是测试字符串的多个条件 this = "allthisstuff" if this.include?("a") # then do all this stuff end if this.include?("f") # then do all this stuff too end if this.include?("s") # also do all this stuff end 有没有更有效的方法来实现这一点,或者堆叠if语句是最好的选择?我会使用带有回调的递归

我想知道最好的方法是测试字符串的多个条件

this = "allthisstuff"

if this.include?("a")
  # then do all this stuff
end
if this.include?("f")
  # then do all this stuff too
end
if this.include?("s")
  # also do all this stuff
end

有没有更有效的方法来实现这一点,或者堆叠
if
语句是最好的选择?

我会使用带有回调的递归方法


由于您正在尝试评估
字符串
,因此最好扩展
字符串
类:

#config/initializers/string.rb #-> should be in /lib 
class String
  def has? *letters
    letters.each do |letter|
      yield letter, self.include?(letter)
    end
  end
end

#app
this = "allthisstuff"
this.has?("a", "f", "s", "d") { |letter,result| puts "#{letter} #{result}" }

# -> a true
# -> f true
# -> s true
# -> d false
上述内容将允许您使用单个块,通过该块,您将能够计算传递的
字母

this.has?("a", "f", "s") do |letter,result|
  if result
    case letter
      when "a"
        # do something
      when "f"
        # do something
    end
  end
end
--

如果您想包含单独的块(对于JS完全可行),那么您应该看看“回调”。尽管回调并非严格意义上的Ruby方式的一部分,但您可以:

#config/initializers/string.rb
class String
  def has? **letters
    letters.each do |letter,lambda|
      lambda.call(letter.to_s, self.include?(letter.to_s))
    end
  end
end

#app
this.has?({
  a: Proc.new {|letter,result| # do something },
  b: Proc.new {|letter,result| # do something else }
})
为了改善这一点,最好在SASS中找到等效的

--

参考文献:


如果您非常关心效率,请不要使用Rails方法。为什么不使用普通的
include?
?你所做的毫无意义。你所拥有的在我看来很好(除了使用
include?
)。如果“then do all this this stuff”很短,你可以写
如果这个。include?(“a”)
,除非这个。include?(“z”)
可以有一个以上的条件是真的吗?@sawa@Cary Swoveland不确定我为什么要在
include?
中添加S@姆萨拉戈萨-是的。在我的代码中,有很多选项是正确的。与简单地执行
%w(afs)相比,这样做的好处是什么?每个{字母}如果包括?(字母)}
?我认为没有必要在这里扩展
String
。我建议扩展
String
,因为op要求
this.include。很容易成为模型,但每次
都必须通过eval对象?这是“a”
。您的方法的问题是,您必须在块中求值。因此,如果OP想要针对10个字母进行测试,那么必须在一个块中包含每个字母的逻辑。虽然我的第一个建议也是这样做的,但第二个建议允许使用单独的回调方法,我想给出一个可以做什么的想法。我在Javascript(针对Ajax)中也做过类似的事情,所以我想看看是否可以用Ruby来做。