Code Challenge Flashcards
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”]
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 }
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)
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).
class ABC def xyz puts "xyz in ABC" end end
for this code, which one is true?
- ABC::new::xyz
- ABC::new.xyz
- ABC.new::xyz
- ABC.new.xyz
- ABC::new::xyz
- ABC::new.xyz
- ABC.new::xyz
- ABC.new.xyz
all are true
“xyz in ABC”
Is the line of code below valid Ruby code? If so, what does it do? Explain your answer.
-> (a) {p a}[“Hello world”]
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)
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(0) returns nil for unsuccessful conditional
A.a(2) returns the square of 2, i.e 4