[英]How to improve this ruby code more idiomatic?
Since the code below looks very old fashion and ugly. 由于下面的代码看起来很老旧又丑陋。 But after playing around this way is only working.
但是在以这种方式玩耍之后才起作用。
def duplicated? url
found = false
current_user.bookmarks.each do |bookmark|
if bookmark.url.eql? url
found = true
end
end
found
end
I eliminated the local var found and the if statement like this 我消除了找到的本地var和类似的if语句
def duplicated? url
current_user.bookmarks.each do |bookmark|
bookmark.url.eql? url
end
end
And it returns wrong expected result. 并且它返回错误的预期结果。
Any idea how to improve it ? 知道如何改进吗? Thanks
谢谢
I think you need Enumerable#any? 我认为您需要Enumerable#any? here.
这里。 It should be preferred to map/include pair, because it doesn't create a temp array and it returns early on first element found.
应该首选map / include对,因为它不会创建临时数组,并且会在找到的第一个元素上早返回。
def duplicated? url
current_user.bookmarks.any?{|b| b.url.eql? url }
end
def duplicated?(url)
current_user.bookmarks.map{|bm| bm.url}.include?(url)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.