Nokogiri: Select content between element A and B

前端 未结 3 985
误落风尘
误落风尘 2020-12-15 01:40

What\'s the smartest way to have Nokogiri select all content between the start and the stop element (including start-/stop-element)?

Check example code below to unde

3条回答
  •  再見小時候
    2020-12-15 02:44

    A way-too-smart oneliner which uses recursion:

    def collect_between(first, last)
      first == last ? [first] : [first, *collect_between(first.next, last)]
    end
    

    An iterative solution:

    def collect_between(first, last)
      result = [first]
      until first == last
        first = first.next
        result << first
      end
      result
    end
    

    EDIT: (Short) explanation of the asterix

    It's called the splat operator. It "unrolls" an array:

    array = [3, 2, 1]
    [4, array]  # => [4, [3, 2, 1]]
    [4, *array] # => [4, 3, 2, 1]
    
    some_method(array)  # => some_method([3, 2, 1])
    some_method(*array) # => some_method(3, 2, 1)
    
    def other_method(*array); array; end
    other_method(1, 2, 3) # => [1, 2, 3] 
    

提交回复
热议问题