ruby - 如果字符串未包含在数组中

时间:2009-12-01 00:32:39

标签: ruby haml each conditional-operator staticmatic

我只想在这里输出一个锚点。如果current_page在数组中,我得到两个(.html和-nf.html)。如果它不在数组中,我会获得与数组中的项目一样多的锚点。

我正在使用StaticMatic

- 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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

好的,所以我认为我们正在检查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" }

抱歉 - 我误解了你在做什么......以为你在做包括?在数组上,但它是一个字符串...: - )