Ruby Tips

Exclamation marks (!) with functions

In general, methods that end in ! indicate that the method will modify the object it’s called on. Ruby calls these “dangerous methods” because they change state that someone else might have a reference to.

“Danger” is relative; For example, gsub! is the dangerous version of gsub. exit! is the dangerous version of exit. flatten! is the dangerous version of flatten. And so forth.

in all case ! does not mean that the method changes its receiver.

“case when” and case equality operator (===)

case a
when 1..5
puts “It’s between 1 and 5”
when 6
puts “It’s 6”
when String
puts “You passed a string”
puts “You gave me #{a} — I have no idea what to do with that.”

The comparison is done by comparing the object in the when-clause with the object in the case-clause using the === operator. That is, it does 1..5 === a and String === a
result = case score
when 0..40 then “Fail”
when 41..60 then “Pass”
when 61..70 then “Pass with Merit”
when 71..100 then “Pass with Distinction”
else “Invalid Score”

then keyword following the when clauses can be replaced with a newline or semicolon. Ruby 1.8 also allows a colon in place of then… But this syntax is no longer allowed in Ruby 1.9.
ruby tutorial links

This entry was posted in Ruby and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s