Forum: Ruby MatchData matchset and matchtree

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Trans (Guest)
on 2007-04-15 20:02
(Received via mailing list)
I think someone asked about/suggested something like this recently. I
think these two methods would make a pretty good addition to the core
library.


 class MatchData

  # Returns [ pre_match, matchtree, post_match ]. (see matchtree)
  #
  #   md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX"
  #   md.to_a      #=> ["XXaabbccddeeffXX", "bb", "ccdd", "dd", "ee"]
  #   md.matchset  #=> ["XXaa", [["bb"], ["cc", ["dd"]], "ee"],
"ffXX"]
  #
  def matchset
     [pre_match, matchtree, post_match]
  end

  # An alternate to #to_a which returns the matches in
  # order corresponding with the regular expression.
  #
  #   md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX"
  #   md.to_a       #=> ["XXaabbccddeeffXX", "bb", "ccdd", "dd", "ee"]
  #   md.matchtree  #=> [["bb"], ["cc", ["dd"]], "ee"]
  #
  def matchtree(index=0)
    ret=[]
    b, e=self.begin(index), self.end(index)
    while (index+=1)<=length
      if index==length || (bi=self.begin(index))>=e
        # we are finished, if something is left, then add it
        ret << string[b, e-b] if e>b
        break
      else
        if bi>=b
          ret << string[b, bi-b] if bi>b
          ret << matchtree(index)
          b=self.end(index)
        end
      end
    end
    return ret
  end

 end
F1d6cc2b735bfd82c8773172da2aeab9?d=identicon&s=25 Nobuyoshi Nakada (Guest)
on 2007-04-18 09:57
(Received via mailing list)
Hi,

Moved to ruby-core.

At Mon, 16 Apr 2007 03:01:46 +0900,
Trans wrote in [ruby-talk:248025]:
> I think someone asked about/suggested something like this recently. I
> think these two methods would make a pretty good addition to the core
> library.

Seems nice, but I'm not sure if the names are best for them.
Any other idea?
45196398e9685000d195ec626d477f0e?d=identicon&s=25 TRANS (Guest)
on 2007-04-19 18:50
(Received via mailing list)
On 4/18/07, Nobuyoshi Nakada <nobu@ruby-lang.org> wrote:
> Seems nice, but I'm not sure if the names are best for them.
> Any other idea?

Can't think of anything better, myself. But certainly feel free to
name them whatever seems more appropriate.

Thanks,
T.
This topic is locked and can not be replied to.