Ruby Quirks (You would amaze at first point)

Right now i am at the stage of learning. (I guess this line applies to every people who are associated with ruby (^o^) since learning never ends )

While studying Ruby i am finding(**still continuing) that language looks quite simple but has its own complex and hidden secrets.

So, i am writing my experience of unexpected or peculiar behavior (Quirks) i have observed or will be going in future in this post.

1) Why following statement results into ‘nil’ ?

expand = defined?( expand ) ? expand : true

Assume that expand encountered here for the first time.

2) In the following Ruby code, x gets the value nil and pqr remains an undefined local variable. Why?

if false
  x = pqr
puts x
puts pqr

3) What is happening in following code and why, how?

x = 5
y = 10
x, y = y, x
puts x
puts y

4) Why expression 1 == 1.0 evaluates to true ?
Check following irb session:

> 1.class   #output Fixnum
> 1.0.class #output Float
> 1 == 1.0  #output true

5) In case of multiple values at right hand side(RHS) of assignment, the rules of parallel assignment come into play. First, all the RHS values evaluated, left to right, and collected into an array (unless they are already an array). This array will be the eventual value returned by the overall assignment. Next, the left hand side (lhs) is inspected. If it contains a single element, the array is assigned to that element otherwise values get corresponding assignment.

a = 1, 2, 3, 4             # => a == [1, 2, 3, 4]  
b = [1, 2, 3, 4] (Array)   # => b == [1, 2, 3, 4]  
c,d = 1,2,3,4              # => c = 1, d = 2

About budhramgurung

I am a self-motivated experienced Software Engineer with good communication and interpersonal skills and has the ability to work independently, can lead, motivate and influence others and can train and mentor others. Has hands-on experience in RoR since Jan, 2012. I am an open source contributor and holds a Master's Degree in Computer Science and experience working as a Software Engineer since August, 2011.

Posted on September 6, 2012, in ruby and tagged , . Bookmark the permalink. Leave a comment.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: