我有以下的逻辑,如果是真的,我将呈现一个部分。
@taxon.tag.present? && @taxon.tag.include?('shirts') || @taxon.tag.present? && @taxon.tag.include?('dibs')我正在尝试以下行为:if taxon.tag is present and includes shirts or dibs
让我的部分。
我不喜欢我重复这么多代码。
我试过@taxon.tag.present? && %w(shirts dibs)include?(@taxon.canonical_tag)不起作用,因为衬衫的标签是:“恤/url/url”如果是“恤”就行了
有什么快速的方法可以重建这个呢?
发布于 2014-11-17 21:40:49
这样做的一种方法是
( (@taxon.tag || []) & ["shirts", "dibs"] ).present?This可能会有帮助。
让我解释一下解决办法:
# @taxon.tag looks like an enumerable, but it could also be nil as you check it with
# .present? So to be safe, we do the following
(@taxon.tag || [])
# will guarentee to return an enumerable
# The & does an intersection of two arrays
# [1,2,3] & [3,4,5] will return 3
(@taxon.tag || []) & ["shirts, "dibs"]
# will return the common value, so if shirts and dibs are empty, will return empty
( (@taxon.tag || []) & ["shirts, "dibs"] ).present?
# should do what you set out to dohttps://stackoverflow.com/questions/26982423
复制相似问题