Ruby — если строка не содержится в массиве
-
22-07-2019 - |
Вопрос
Я хочу вывести здесь только один якорь.Если current_page находится в массиве, я получаю два (.html и -nf.html).Если его нет в массиве, я получаю столько привязок, сколько элементов в массиве.
Я использую СтатикМатик.
- if page_options[:current_index] < page_options[:total_index] && page_options[:current_index] > 0
// loop through the pre-flash array and if current page matches, add -nf
- page_options[:pre_flash] = ['string_one-nf', 'string_two-nf', 'string_three-nf']
- page_options[:pre_flash].each do |each_string|
- if current_page.include? each_string
%li
%a{ :href => "page#{page_options[:current_index]}-nf.html", :class => "next" }
Next
- else
%li
%a{ :href => "page#{page_options[:current_index]}.html", :class => "next" }
Next
Решение
unless current_page.include? the_string
Редактировать:
Вы можете прервать каждый цикл, если хотите, чтобы ваша первая находка была единственной.Но теперь это выглядит немного странно, потому что вы итерации над массивом и ломаются после первого элемента, независимо от того, что произойдет.Я вообще решаю вашу проблему?
options[:pre_flash] = ['string_one-nf', 'string_two-nf', 'string_three-nf']
page_options[:pre_flash].each do |each_string|
if current_page.include? each_string
%li
%a{ :href => "page#{page_options[:current_index]}-nf.html", :class => "next" }
# This is the last ancor
break
else
%li
%a{ :href => "page#{page_options[:current_index]}.html", :class => "next" }
# This is the last ancor
break
end
end
Другие советы
Хорошо, я думаю, мы проверяем, что ни одно из page_options [: current_index] не является подстрокой current_page.
if page_options[:current_index] < page_options[:total_index] && page_options[:current_index] > 0
found_item = false
// loop through the pre-flash array and if current page matches, add -nf
- page_options[:pre_flash] = ['string_one-nf', 'string_two-nf', 'string_three-nf']
- page_options[:pre_flash].each do |each_string|
- if current_page.include? each_string
found_item = true
%li
%a{ :href => "page#{page_options[:current_index]}-nf.html", :class => "next" }
Next
# do whatever you need to get out of the staticmatic block...
- if !found_item
%li
%a{ :href => "page#{page_options[:current_index]}.html", :class => "next" }
Извините - я неправильно понял, что вы делали ... думал, что вы делаете включение? в массиве, но это была строка ...: -)