Tatva-Artha

meaning of "it"

Ruby Interview Questions

without comments

I’ve been attending a few Ruby interviews recently. Here are a few questions that I liked being asked. The answers are all mine and may not be all correct.

# Question: Invert the following array
{:a => 1, :b => 2}
# Expected Result: 
{1=>:a, 2=>:b}
 
# Answer:
Hash[{:a => 1, :b => 2}.collect {|k,v| [v,k] }]
# OR
{:a => 1, :b => 2}.inject({}) { |r,e| r.merge({e[1] => e[0]}) }
# Question: What will following code return
{:a => 1, :b => 2}.to_a
# Answer:
[[:a, 1], [:b, 2]]
# Question: How to you quickly determine if a given hash is identity hash or not?
# (Identity Hash is where key == value. For example, {:a => :a, :b => :b})
hash.keys == hash.values
# (Note: hash.keys and hash.values will return the elements in matching order as long as hash is not modified between those 2 calls)
# Question: What is the difference between following to codes?
x = 'a'
x += 'b'
# and
x = 'a'
x << 'b'
# Answer: Nothing. They both return the same result
x = 'ab'
# Question: What will following code return
''.to_sym
# Answer: ArgumentError: interning empty string
# (in other words, an empty string cannot be symbolized/internalized)
# Question: What will the following code return
begin
  ''.to_sym
rescue => e
  5
ensure
  6
end
# Answer:
5
# Note: logic inside ensure does get executed but it still returns the final output of rescue block! This is different from Java, where anything returned from inside finally will override the original return value.
# Question: Given following classes, specify the parent-child inheritance relationship
Class
Object
Module
String
# Answer:

# Question: What will following code return?
x = 1
Array === x
# Answer:
false
# === is a equality operator used for case/when statement.
# Question: What will following code return?
x = []
Array === x
# Answer:
true
http://www.tatvartha.com/wp-content/plugins/sociofluid/images/digg_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/reddit_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/stumbleupon_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/delicious_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/google_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/twitter_16.png

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Written by Sharad

October 24th, 2009 at 5:18 am

Posted in All

Leave a Reply