tags:

views:

34

answers:

1

i have the value of targetfilename =/mnt/usb/mpeg4Encoded.mpeg4 how this pattren matching if (targetfilename.match(/^\//))

                              puts "amit"
                          else 
                                puts "ramit"

the o/p is ramit but how cud anybody help me in figuring out ... how this pattren matching works??

A: 
if targetfilename.match(/^V/)
  puts "amit"
else
  puts "ramit"
end

# result:
# "amit"

Why is this? This is because targetfilename.match(/^V/) outputs a Matchdata object (click on the link for a full description of this object). This is an object that contains all of the information that is in the "matching". If there is no match, no MatchData object is returned, because there's nothing to return. Instead, you get nil.

When you use if, if it tries to compare a nil, it treats it the same way as false.

Basically, any "actual" value (besides false) is treated the same way as true. Basically, it's asking

if (there's anything here)
  do_this
else
  do_something_else
end

Again, let me reiterate:

If the thing after if is either false or nil, the if statement resolves to the "else". If it's anything else, it resolves as if it had gotten a "true" statement.


Regular Expressions

/^V/ is what is called a "Regular Expression"; the // is a Regexp literal the same way that the "" is a String literal, and Regexps are represented by the Regexp class the same way that strings are represented by the String class.

The actual "regular expression" is what's between the slashes -- ^V. This is saying:

  • ^: the start of a string
  • V: a capital letter V

So, /^V/ will match any cases of the capital letter "V" at the beginning of a string.

What else can you put in a regular expression? What are the special characters? Try this regexp cheat sheet

Also, some great tools:

  • Rubular -- enter in your regular expression, and then a same text, and see what matches.
  • Strfriend -- enter in a regular expression and see it "visually" represented.
Justin L.
thanks JUSTIN ...but justin what i want to no is how (/^\//) is working actully i already known abt the fact like matchdataobject and nil value
amit singh tomar
edited post to add how regular expressions worked
Justin L.