$-variables and regexp

A

ako...

hello,

if i indeed want to start using MatchData instead of the "warts" such
as $-variables in regular expressions, how do i go about writing code
blocks for String#sub et al if i want to get a match for a particular
group?

example:

puts 'a-b-c-'.gsub(/(.)-/) { $1 + '_' }

thanks
konstantin
 
N

Neil Stevens

ako... said:
hello,

if i indeed want to start using MatchData instead of the "warts" such
as $-variables in regular expressions, how do i go about writing code
blocks for String#sub et al if i want to get a match for a particular
group?

example:

puts 'a-b-c-'.gsub(/(.)-/) { $1 + '_' }

puts 'a-b-c-'.gsub(/(.)-/) { |str| str + '_' }

Though gsub never does give you access to MatchData. MatchData is used
when you do something like this:

matchData = /([[:alpha:]]+):([[:alpha:]]+)/.match('abc:xyz')
=> MatchData
matchData[1]
=> 'abc'
matchData[2]
=> 'xyz'
 
A

ako...

puts 'a-b-c-'.gsub(/(.)-/) { |str| str + '_' }

i think this is incorrect. id appends an underscore. i need to replace
it.
 
N

Neil Stevens

ako... said:
i think this is incorrect. id appends an underscore. i need to replace
it.

Ah, sorry, mis-read what yours did.

It appears that gsub has been written to depend on the magic variables,
because it gives you no other means of accessing the MatchData.

So, to use gsub like this and get the MatchData, your guess is as good
as mine as to how to get to it. Just hold down shift and pound on the
keyboard until you guess the right bit of magic punctuation.

Sorry I couldn't help more,
 
J

James Edward Gray II

hello,

if i indeed want to start using MatchData instead of the "warts" such
as $-variables in regular expressions, how do i go about writing code
blocks for String#sub et al if i want to get a match for a particular
group?

example:

puts 'a-b-c-'.gsub(/(.)-/) { $1 + '_' }

The MatchData object is also placed in a global variable, but I won't
show it here since it is a punctuation variable and you requested
something different.

Not a direct answer, but you can just use a replacement string in
this case:

'a-b-c-'.gsub(/(.)-/, '\1_')

Or even no regular expression at all:

'a-b-c-'.tr('-', '_')

Hope that helps.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,647
Latest member
NelleMacy9

Latest Threads

Top