Home > Blockchain >  Highlight specific elements of an embedded ruby array and display it as one sentence
Highlight specific elements of an embedded ruby array and display it as one sentence

Time:12-12

I would like to display a list of items as a sentence with the just some of those items highlighted in a different color. <span ></span>.

I've managed to display it as two separate sentences (arrays) although I could not find a solution to join them both and highlight only the desired ones.

Although the code below worked for sorting I can't manage to find a satisfactory solution to display it.

# items = ['flour', 'oil', 'egg', 'salt']
# in_stock = ['flour', 'oil']
# items_in_stock = []
# items_not_in_stock = []

items.each do |item|
 if in_stock.include?(item)
  items_in_stock << item
 elsif !in_stock.include?(item)
  items_not_in_stock << item
 end
end

# items_in_stock = ['flour', 'oil']
# items_not_in_stock = ['egg', 'salt']
<p>
 <%= items_in_stock.to_sentence %>
 <strong>
  <%= items_not_in_stock.to_sentence %>
 </strong>
</p>

As an outcome I get two sentences which is not ideal as it's supposed to be displayed as a single sentence with a few words highlighted (used strong just for eg.)

=> Flour and oil Egg and salt

I've also though of doing the following:

#checked_items = []
items.each do |item|
 if in_stock.include?(item)
  checked_items << item
 elsif !in_stock.include?(item)
  checked_items << "<span class='red'>#{item}</span>"
 end
end

But then I realize that it doesn't work, having as a result:

<p>
<%= checked_items.to_sentence %>
</p>

#=> Flour, oil, <span class='red'> egg </span> and <span class='red'> salt </span>

This is my first question on here, hope it's well explained. Thanks in advance for your help.

CodePudding user response:

You can use something like:

items = ['flour', 'oil', 'egg', 'salt']
in_stock = ['flour', 'oil']

decorated_items = items.map do |item|
  if in_stock.include?(item)
    item
  else
    "<span class='red'>#{item}</span>" # you can also use: tag.span(item, class: 'red')
  end
end

# => ["flour", "oil", "<span class='red'>egg</span>", "<span class='red'>salt</span>"]

Here you will have an array, if you want to display them in the view layer (helpers or views), you'll need to safely join them:

safe_join(decorated_items) # which is better than decorated_items.join.html_safe
  • Related