红宝石重构包含?这需要多个字符串



我有以下逻辑,如果为真,我将呈现部分。

@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)但不起作用,因为衬衫的标签是:"衬衫/网址/网址",如果是"衬衫"就可以工作了

重构

它的快速方法是什么?

一种方法是

( (@taxon.tag || []) & ["shirts", "dibs"] ).present?

这可能会有所帮助。

让我尝试解释解决方案:

# @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 do

最新更新