Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does this ruby do?

unless (place =~ /^\./) == 0

I know the unless is like if not but what about the condtional?

like image 837
Matt Elhotiby Avatar asked Jan 08 '11 05:01

Matt Elhotiby


2 Answers

=~ means matches regex

/^\./ is a regular expression:

/.../ are the delimiters for the regex

^ matches the start of the string or of a line (\A matches the start of the string only)

\. matches a literal .

like image 78
richo Avatar answered Sep 24 '22 12:09

richo


It checks if the string place starts with a period ..

Consider this:

p ('.foo' =~ /^\./) == 0 # => true
p ('foo' =~ /^\./) == 0 # => false

In this case, it wouldn't be necessary to use == 0. place =~ /^\./ would suffice as a condition:

p '.foo' =~ /^\./ # => 0 # 0 evaluates to true in Ruby conditions
p 'foo' =~ /^\./ # => nil

EDIT: /^\./ is a regular expression. The start and end slashes denotes that it is a regular expression, leaving the important bit to ^\.. The first character, ^ marks "start of string/line" and \. is the literal character ., as the dot character is normally considered a special character in regular expressions.

To read more about regular expressions, see Wikipedia or the excellent regular-expressions.info website.

like image 37
vonconrad Avatar answered Sep 23 '22 12:09

vonconrad