首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >红宝石重构包括?包含多个字符串的

红宝石重构包括?包含多个字符串的
EN

Stack Overflow用户
提问于 2014-11-17 21:36:19
回答 1查看 121关注 0票数 1

我有以下的逻辑,如果是真的,我将呈现一个部分。

代码语言:javascript
复制
@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”如果是“恤”就行了

有什么快速的方法可以重建这个呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-17 21:40:49

这样做的一种方法是

代码语言:javascript
复制
( (@taxon.tag || []) & ["shirts", "dibs"] ).present?

This可能会有帮助。

让我解释一下解决办法:

代码语言:javascript
复制
# @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
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26982423

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档