Home>

I want to store the variable obtained by named capture in the list or array again.
What should I do?

texts = [
  '<hoge><fuga>',
  '<ruby ​​><parl>'
]
pattern =/\ A<(?<Arg1>\ w +)><(?<Arg2>\ w +)>/
texts.each {| t |
  match = t.match (pattern)
  puts match.named_captures
  # Store in list (or array) here
  # matchList.add (match)
  #
}
# Thing I want to do
# matchList.each {| ma2 |
# puts ma2.Arg1
# puts ma2.Arg2
#}
You might say

puts ma2.Arg1is in the loop oftexts.each,
Originally I want to write a long process here, so I want to deliver the matched data to others.
However, I am in trouble without knowing how it can be handled.

Please give me an answer.


ruby ​​version: 2.5.1p57

  • Answer # 1

    It'smap.

    matchList =
    texts.map {| t |
      match = t.match (pattern)
      puts match.named_captures
      # Store in list (or array) here
      match.named_captures
    }
    matchList.each {| ma2 |
      puts ma2 ["Arg1"]
      puts ma2 ["Arg2"]
    }

  • Answer # 2

    How about creating an empty array and adding it withpush?

    matchList = []
    texts.each {| t |
      match = t.match (pattern)
      puts match.named_captures
      # Store in list (or array) here
      matchList.push (match.named_captures)
    }
    matchList.each {| ma2 |
      puts ma2 ["Arg1"]
      puts ma2 ["Arg2"]
    }