Robert Klemme
3/15/2009 7:09:00 PM
On 15.03.2009 18:57, Power One wrote:
> OK, I'm still extremely new to Ruby, so if my question is stupid, please
> be gentle :).
It's not stupid at all. Regular expressions have a bit of a learning
curve, especially if one lacks the formal theory of computer languages.
> The code below is an example from a ruby book, and I look at it, I
> understand most of it, but what I don't understand is why the
> author/ruby-expert has \b in the regular expression (I know it's a
> backspace),
No, it's not in this context. As Michael pointed out, it's a word
boundary anchor, one of several zero width assertions that you can have
in your regular expression. These assertions do not contain characters
when matching but they only match in certain places, in the case of \b
at a word boundary (i.e. the character before is a word character and
the one after a non word character or the other way round).
> but why match for a backspace especially it's outside of the
> bracket, and why the brackets? In this context, I'm confused! I'm
> talking about line number 3! Any clarification or insight would be
> really helpful to me. Thank you!
>
> class WordPlay
> def self.switch_pronouns(text)
> text.gsub(/\b(I am|You are|I|You|Me|Your|My)\b/i) do |pronoun|
The capturing group in this case is not really needed but you need
grouping because of precedence rules and the presence of "|" inside the
expression. For the non capturing version you can do
/\b(?:I am|You are|I|You|Me|Your|My)\b/i
Kind regards
robert