Class: MatchData

Inherits:
Object
  • Object
show all
Defined in:
lib/common/class_exts/matchdata.rb

Overview

extension to class MatchData 2025-03-14

Instance Method Summary collapse

Instance Method Details

#to_hashHash

Note:

This method strips whitespace from each capture and converts numeric captures to integers.

Converts the MatchData object to a hash.

Examples:

match_data = /(\d+)/.match("123")
hash = match_data.to_hash
puts hash # => {"0"=>"123"}

Returns:

  • (Hash)

    a hash where keys are the names of the captures and values are the corresponding captures.

Raises:

  • (TypeError)

    if names or captures are not enumerable.



28
29
30
31
32
# File 'lib/common/class_exts/matchdata.rb', line 28

def to_hash
  Hash[self.names.zip(self.captures.map(&:strip).map do |capture|
    if capture.is_i? then capture.to_i else capture end
  end)]
end

#to_structOpenStruct

Converts the MatchData object to an OpenStruct.

Examples:

match_data = /(\w+)/.match("hello")
struct = match_data.to_struct
puts struct[0] # => "hello"

Returns:

  • (OpenStruct)

    an OpenStruct representation of the MatchData.



12
13
14
# File 'lib/common/class_exts/matchdata.rb', line 12

def to_struct
  OpenStruct.new to_hash
end