Take the 2-minute tour ×

I'm trying the same super simple regex on Rubular.com and my VM Linux with Ruby 1.9.2 I dont' know why I'm getting different outputs: VM:

my_str = "Madam Anita"
puts my_str[/\w/]

this Outputs: Madam

on Rubular it outputs: MadamAnita Rubular: http://www.rubular.com/r/qyQipItdes

I would love some help. I stuck here. I will not be able to test my code for the hw1.

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

No, it doesn't really. It matches all characters in "Madam" and "Anita", but not the space. The problem you are having is that my_str[/\w/] only returns a single match for the given regular expression, whereas Rubular highlights all possible matches.

If you need all occurrences, you could do this:

1.9.3p194 :002 > "Madam Anita".scan(/\w+/)
 => ["Madam", "", "Anita", ""] 
share|improve this answer
Use \w+ instead...empty groups are usually not so useful. –  nneonneo Oct 7 '12 at 0:44
understood. thanks –  frenesim Oct 7 '12 at 0:53
add comment

Actually, \w matches a single character. The result in Rubular contains spaces between adjacent characters to tell you this (though I wish they'd also make the highlighting more obvious...). Compare with the output from matching \w+, which matches two strings (Madam and Anita).

share|improve this answer
thanks for notice this out. I would like a better highlighting also. –  frenesim Oct 7 '12 at 0:52
add comment

Your Answer


