我正在使用 Rails 3.2.3 和 Ruby 1.9.3p0。
我发现我经常需要确定某个字符串是否出现在选项列表中。看来我可以使用 Ruby 数组 .include method :
<% if ['todo','pending','history'].include?(params[:category]) %>
或正则表达式 equals-tilde match shorthand用竖线分隔选项:
<% if params[:category] =~ /todo|pending|history/ %>
就性能而言,一个比另一个好吗?
还有更好的方法吗?
最佳答案
总结:Array#include? 包含 String 元素,在接受和拒绝输入时均胜出,对于您的示例只有三个可接受的值。对于要检查的更大的集合,看起来 Set#include? 和 String 元素可能会获胜。
如何测试
我们应该根据经验对此进行测试。
您可能还需要考虑以下几个备选方案:预编译的正则表达式、符号列表和带有 String 元素的 Set。
我认为性能还可能取决于您的大部分输入是否落入预期集合并被接受,或者大多数输入是否落在集合之外并被拒绝。
这是一个实证测试脚本:
require 'benchmark'
require 'set'
strings = ['todo','pending','history']
string_set = Set.new(strings)
symbols = strings.map(&:to_sym)
regex_compiled = Regexp.new(strings.join("|"))
strings_avg_size = (strings.map(&:size).inject {|sum, n| sum + n}.to_f / strings.size).to_i
num_inputs = 1_000_000
accepted_inputs = (0...num_inputs).map { strings[rand(strings.size)] }
rejected_inputs = (0...num_inputs).map { (0..strings_avg_size).map { ('a'...'z').to_a[rand(26)] }.join }
Benchmark.bmbm(40) do |x|
x.report("Array#include?, Strings, accepted:") { accepted_inputs.map {|s| strings.include?(s) } }
x.report("Array#include?, Strings, rejected:") { rejected_inputs.map {|s| strings.include?(s) } }
x.report("Array#include?, Symbols, accepted:") { accepted_inputs.map {|s| symbols.include?(s.to_sym) } }
x.report("Array#include?, Symbols, rejected:") { rejected_inputs.map {|s| symbols.include?(s.to_sym) } }
x.report("Set#include?, Strings, accepted:") { accepted_inputs.map {|s| string_set.include?(s) } }
x.report("Set#include?, Strings, rejected:") { rejected_inputs.map {|s| string_set.include?(s) } }
x.report("Regexp#match, interpreted, accepted:") { accepted_inputs.map {|s| s =~ /todo|pending|history/ } }
x.report("Regexp#match, interpreted, rejected:") { rejected_inputs.map {|s| s =~ /todo|pending|history/ } }
x.report("Regexp#match, compiled, accepted:") { accepted_inputs.map {|s| regex_compiled.match(s) } }
x.report("Regexp#match, compiled, rejected:") { rejected_inputs.map {|s| regex_compiled.match(s) } }
end
结果
Rehearsal ---------------------------------------------------------------------------
Array#include?, Strings, accepted: 0.210000 0.000000 0.210000 ( 0.215099)
Array#include?, Strings, rejected: 0.530000 0.010000 0.540000 ( 0.543898)
Array#include?, Symbols, accepted: 0.330000 0.000000 0.330000 ( 0.337767)
Array#include?, Symbols, rejected: 1.870000 0.050000 1.920000 ( 1.923155)
Set#include?, Strings, accepted: 0.270000 0.000000 0.270000 ( 0.274774)
Set#include?, Strings, rejected: 0.460000 0.000000 0.460000 ( 0.463925)
Regexp#match, interpreted, accepted: 0.380000 0.000000 0.380000 ( 0.382060)
Regexp#match, interpreted, rejected: 0.650000 0.000000 0.650000 ( 0.660775)
Regexp#match, compiled, accepted: 1.130000 0.080000 1.210000 ( 1.220970)
Regexp#match, compiled, rejected: 0.630000 0.000000 0.630000 ( 0.640721)
------------------------------------------------------------------ total: 6.600000sec
user system total real
Array#include?, Strings, accepted: 0.210000 0.000000 0.210000 ( 0.219060)
Array#include?, Strings, rejected: 0.430000 0.000000 0.430000 ( 0.444911)
Array#include?, Symbols, accepted: 0.340000 0.000000 0.340000 ( 0.341970)
Array#include?, Symbols, rejected: 1.080000 0.000000 1.080000 ( 1.089961)
Set#include?, Strings, accepted: 0.270000 0.000000 0.270000 ( 0.281270)
Set#include?, Strings, rejected: 0.400000 0.000000 0.400000 ( 0.406181)
Regexp#match, interpreted, accepted: 0.370000 0.000000 0.370000 ( 0.366931)
Regexp#match, interpreted, rejected: 0.560000 0.000000 0.560000 ( 0.558652)
Regexp#match, compiled, accepted: 0.920000 0.000000 0.920000 ( 0.915914)
Regexp#match, compiled, rejected: 0.620000 0.000000 0.620000 ( 0.627620)
结论
(见上面的总结)
经过深思熟虑,符号数组对于被拒绝的输入会非常慢,因为在进行检查之前,这些随机字符串中的每一个都必须驻留在符号表中。
即使经过深思熟虑,编译后的 Regexp 的性能也会如此糟糕,这对我来说意义不大,尤其是与在代码中解释为文字的 Regexp 相比。谁能解释为什么它表现如此糟糕?
关于Ruby on Rails regexp equals-tilde 与 array include 用于检查选项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11905925/
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案
我已经在Sinatra上创建了应用程序,它代表了一个简单的API。我想在生产和开发上进行部署。我想在部署时选择,是开发还是生产,一些方法的逻辑应该改变,这取决于部署类型。是否有任何想法,如何完成以及解决此问题的一些示例。例子:我有代码get'/api/test'doreturn"Itisdev"end但是在部署到生产环境之后我想在运行/api/test之后看到ItisPROD如何实现? 最佳答案 根据SinatraDocumentation:EnvironmentscanbesetthroughtheRACK_ENVenvironm
我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查
我的日期格式如下:"%d-%m-%Y"(例如,今天的日期为07-09-2015),我想看看是不是在过去的七天内。谁能推荐一种方法? 最佳答案 你可以这样做:require"date"Date.today-7 关于ruby-检查日期是否在过去7天内,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/32438063/