Code Challenge Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Write a function that sorts the keys in a hash by the length of the key as a string. For instance, the hash:

{ abc: ‘hello’, ‘another_key’ => 123, 4567 => ‘third’ }

should result in:

[“abc”, “4567”, “another_key”]

A

The most straightforward answer would be of the form:

hsh.keys.map(&:to_s).sort_by(&:length)
or:

hsh.keys.collect(&:to_s).sort_by { |key| key.length }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Consider the following two methods:

def times_two(arg1);
puts arg1 * 2;
end

def sum(arg1, arg2);
puts arg1 + arg2;
end
What will be the result of each of the following lines of code:

times_two 5
times_two(5)
times_two (5)
sum 1, 2
sum(1, 2)
sum (1, 2)
A
times_two 5 # 10
times_two(5) #10
times_two (5) #10
sum 1, 2 #3
sum(1, 2) #3
sum (1, 2) # syntax error

The problem is the space between the method name and the open parenthesis. Because of the space, the Ruby parser thinks that (1, 2) is an expression that represents a single argument, but (1, 2) is not a valid Ruby expression, hence the error.

Note that the problem does not occur with single argument methods (as shown with our timesTwo method above), since the single value is a valid expression (e.g., (5) is a valid expression which simply evaluates to 5).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
class ABC
  def xyz
    puts "xyz in ABC"
  end
end

for this code, which one is true?

  1. ABC::new::xyz
  2. ABC::new.xyz
  3. ABC.new::xyz
  4. ABC.new.xyz
A
  1. ABC::new::xyz
  2. ABC::new.xyz
  3. ABC.new::xyz
  4. ABC.new.xyz

all are true

“xyz in ABC”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Is the line of code below valid Ruby code? If so, what does it do? Explain your answer.

-> (a) {p a}[“Hello world”]

A

The -> operator creates a new Proc, which is one of Ruby’s function types. (The -> is often called the “stabby proc”.

his particular Proc takes one parameter (namely, a). When the Proc is called, Ruby executes the block p a, which is the equivalent of puts(a.inspect)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
class A
  def self.a(b)
    if b > 0
      b * b
    end
  end
end

What will be the values of:

var1 = A.a(0)
var2 = A.a(2)
A

A.a(0) returns nil for unsuccessful conditional

A.a(2) returns the square of 2, i.e 4

How well did you know this?
1
Not at all
2
3
4
5
Perfectly