Search code examples
rubyregexrubular

Ruby Regex Different from Rubular


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.


Solution

  • 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", ""]