简体   繁体   English

Ruby重构包括吗? 需要多个字符串

[英]Ruby refactor include? that takes in multiple strings

I have the following logic, if true I'm rendering a partial. 我有以下逻辑,如果为true,则表示部分渲染。

@taxon.tag.present? && @taxon.tag.include?('shirts') || @taxon.tag.present? && @taxon.tag.include?('dibs')

I'm trying have the following behaviour: if taxon.tag is present and includes shirts or dibs 我正在尝试以下行为: if taxon.tag is present and includes shirts or dibs

render my partial. 渲染我的部分。

I don't like that I'm repeating code so much. 我不喜欢我重复很多代码。

I tried @taxon.tag.present? && %w(shirts dibs)include?(@taxon.canonical_tag) 我尝试了@taxon.tag.present? && %w(shirts dibs)include?(@taxon.canonical_tag) @taxon.tag.present? && %w(shirts dibs)include?(@taxon.canonical_tag) didn't work because tag for shirts is: "shirts/url/url" it would work if it was "shirts" @taxon.tag.present? && %w(shirts dibs)include?(@taxon.canonical_tag)不起作用,因为衬衫的标签为:“ shirts / url / url”如果是“ shirts”则可以使用

what would be a quick way to refactor this? 什么是重构此方法的快速方法?

One way to do this would be 一种方法是

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

This might be helpful. 可能会有所帮助。

Let me try to explain the solution: 让我尝试解释解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM