简体   繁体   中英

Ruby refactor include? that takes in multiple strings

I have the following logic, if true I'm rendering a partial.

@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

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) didn't work because tag for shirts is: "shirts/url/url" it would work if it was "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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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