A few code snippets on how an XPath method could work

a = [5,7,2,3]

# xpath = '7'
a.select {|x| x == 7} #=> [7]

# ----------------

a = [5,7,2,3,7]

# xpath = '7'
a.select {|x| x == 7} #=> [7,7]

# -----------------

a = [[5],[7],[2,[[5],[6]]],[3],[7]]

# xpath = '7'
a.select {|x| x.first == 7} #=> [[7],[7]]

# ------------------

a = [[5],[7],[2,[[5],[6]]],[3],[7]]

xpath = '2'
a.select {|x| x.first == 2} #=> [[2, [[5], [6]]]]


# -- nested xpath ----------------

a = [[5],[7],[2,[[5],[6]]],[3],[7]]

def select(a, raw_xpath)
  xpath = raw_xpath.split('/')
  y = xpath.shift.to_i
  puts 'a : ' + a.inspect
  puts 'y : '  + y.inspect
  a2 = a.select {|x| x.first == y} #=> [[2, [[5], [6]]]]
  puts 'a2 : ' + a2.inspect
  if xpath.length > 0 then
    r = select(a2.first.last, xpath.join('/'))
    puts 'r : ' + r.inspect
  end
end

select(a, '2/5')



# -- nested xpath (2 levels) ----------------

a = [[5],[7],[2,[[5],[6,[8,1,6]]]],[3,[[4,[[9],[6],[1,[4]]]],[6]]],[7]]

def select(a, raw_xpath)
  xpath = raw_xpath.split('/')
  y = xpath.shift.to_i
  puts 'a : ' + a.inspect
  puts 'y : '  + y.inspect
  a2 = a.select {|x| x.first == y} #=> [[2, [[5], [6]]]]
  puts 'a2 : ' + a2.first.last.inspect if a2.first
  if xpath.length > 0 and a2.first then
    
    r = select(a2.first.last, xpath.join('/'))
    puts 'r : ' + r.inspect
  end
end

select(a, '3/4/1')

Tags:
Source:
2117hrs.txt
Published:
01-07-2013 21:17