你有什么建议让这if
条件缩短(更优雅)莫名其妙吗?对红宝石“if”语句的评论
if (@path.start_with? "scp" || @path.start_with? "http")
@source = "url"
else
@source = "local"
end
如果我有几个更多的前缀来检查(比如说ftp1,ftp2和ftp3)怎么办?
你有什么建议让这if
条件缩短(更优雅)莫名其妙吗?对红宝石“if”语句的评论
if (@path.start_with? "scp" || @path.start_with? "http")
@source = "url"
else
@source = "local"
end
如果我有几个更多的前缀来检查(比如说ftp1,ftp2和ftp3)怎么办?
可以采取多个字符串作为参数
@source = @path.start_with?("scp", "http") ? "url" : "local"
它可能是有道理的前缀首先提取到一个数组时,名单会越来越长:
URL_PREFIXES = %w[ scp http ]
我能想到的serveral的办法使用那个URL_PREFIXES
不变。例如,我经常喜欢if...else
块以上的可读性原因之一内胆:
if URL_PREFIXES.any? { |p| @path.start_with?(p) }
@source = 'url'
else
@source = 'local'
end
或者这样:
@source = 'local'
@source = 'url' if URL_PREFIXES.any? { |p| @path.start_with?(p) }
还是首先确定前缀:
prefix = @path.split(':').first
@source = URL_PREFIXES.include?(prefix) ? 'url' : 'local'
如果您在使用Rails工作你可能想写下这个:
prefix = @path.split(':').first
@source = prefix.in?(URL_PREFIXES) ? 'url' : 'local'
你想要这些新前缀的结果是什么? – engineersmnky
对于代码评论还有另一个网站:http://codereview.stackexchange.com – Meier
@Meier谢谢你,我从来没有见过这个网站!真棒:) – valadzko