10 Excellent Ruby and Rails Interview Questions¹
Here is a collection of 10 interview questions one can use to prove that the interviewee knows nothing about Ruby.
Before opening a link with the correct answer, please spend at least 5 minutes and try to come up with an answer by yourself.
1. Supersonic Future
$ ruby -r./magic.rb -e 'maybe_yes_maybe_no = magic; if maybe_yes_maybe_no then puts "YES" else puts "NO" end'
YES
NO
As you see, both branches of the if
are executed. In this question and in any
other question in this post, standard Ruby distribution is used.
The task is to implement magic.rb
.
Hint.
Now, think again.
Giving up? Here’s the answer.
2. Point-free
duplicate = ...
duplicate.(20) # => [20, 20]
duplicate.(:x) # => [:x, :x]
Implement duplicate
. There is a limitation: using arbitrary local variables
(including proc/lambda/block/method params) is not allowed. For example,
the following solutions are not acceptable:
duplicate = proc { |x| [x, x] }
duplicate = method(def f(x) [x, x]; end)
3. Forty Two
h = {}
h.inspect.size # => 2
v = ...
h[v] = v
h.inspect.size # => 14
h[v] = v
h.inspect.size # => 28
h[v] = v
h.inspect.size # => 42
What is v
equal to?
4. Binary Blindness
"1011".b
is equal to
11
"1111110011"
"11"
1011
"1011"
String
doesn’t have a method namedb
undefined
5. ActiveRails
Let’s assume u
is a newly created instance of a usual AR model User < ActiveRecord::Base
with timestamp columns.
What is u.updated_at -u.created_at
equal to?
0.0
0
- Non-negative integer number
- Non-negative floating point number
undefined
- ___ your answer
If you think you know the answer, write it down first and then compare with the correct answer.
6. Quantum Computing
[0,1].first(&:nonzero?)
evaluates to
0
1
- Runtime error
undefined
7. Referential Transparency
Implement MyClass
such that
case 5 when MyClass then true else false end
# => true
case 5 when MyClass then true else false end
# => false
case 5 when MyClass then true else false end
# => true
8. Go Meta
class A
end
A.class_eval do
extend Module.new do
def foo
:bar
end
end
end
A.foo
returns…
:bar
nil
undefined
- __ your answer.
9. Matrix Multiplication
[ 10 ] [ 0 ] [ 01 ]
returns…
0
1
2
10
-1
10001
- Syntax error
- Runtime error
undefined
10. Action Unpack
Construct an object liar
using only standard Rails classes and not using metaprogramming (not even (re)defining classes and methods), for which the following is true:
liar = ...
liar.nil? # => true
!liar # => false
Bonus: C++
def f(xs, ys)
xs.reject! do |x|
ys.any? { |y| y[:cnt] += x[:cnt] if x != y }
end
end
a = [{cnt: 4}, {cnt: 2}]
f(a, a)
a # => ???
What a
will be equal to as a result?
[{cnt: 4}, {cnt: 2}]
[{cnt: 4}]
[{cnt: 2}]
[{cnt: 6}]
[]
- Runtime error
undefined
Final word
If your interviewee knows more than a half of these questions - they are a perfect
candidate for a Ruby position solving stupid riddles.
¹ Never ever ask these questions during an actual interview.