更高效 ruby if case
More efficient ruby if case
我想知道在多个条件下测试字符串的最佳方法是什么。
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
语句是否是最佳选择?
我会使用带回调的递归方法。
由于您正在尝试评估 String
,因此最好扩展 String
class:
#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
以上将允许您使用单个块,通过它您将能够评估传递的 letter
:
this.has?("a", "f", "s") do |letter,result|
if result
case letter
when "a"
# do something
when "f"
# do something
end
end
end
--
如果您想包含单独的块(使用 JS 完全可行),您需要查看 "callbacks"。虽然回调严格来说并不是 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
中找到 arglist
的等价物
--
参考文献:
- How to implement a "callback" in Ruby?
- Passing multiple code blocks as arguments in Ruby
我想知道在多个条件下测试字符串的最佳方法是什么。
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
语句是否是最佳选择?
我会使用带回调的递归方法。
由于您正在尝试评估 String
,因此最好扩展 String
class:
#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
以上将允许您使用单个块,通过它您将能够评估传递的 letter
:
this.has?("a", "f", "s") do |letter,result|
if result
case letter
when "a"
# do something
when "f"
# do something
end
end
end
--
如果您想包含单独的块(使用 JS 完全可行),您需要查看 "callbacks"。虽然回调严格来说并不是 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
中找到arglist
的等价物
--
参考文献:
- How to implement a "callback" in Ruby?
- Passing multiple code blocks as arguments in Ruby