0
0
Rubyprogramming~10 mins

Open classes (reopening classes) in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to reopen the String class and add a method.

Ruby
class String
  def [1]
    "Hello, " + self
  end
end

puts "World".greet
Drag options to blanks, or click blank then click option'
Agreet
Bhello
Csay_hello
Dgreeting
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name different from the one called on the string.
Forgetting to reopen the class before defining the method.
2fill in blank
medium

Complete the code to reopen the Integer class and add a method that doubles the number.

Ruby
class Integer
  def [1]
    self * 2
  end
end

puts 5.double
Drag options to blanks, or click blank then click option'
Amultiply
Btwice
Ctimes_two
Ddouble
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name that does not match the call.
Not returning the correct calculation.
3fill in blank
hard

Fix the error in reopening the Array class to add a method that returns the first element doubled.

Ruby
class Array
  def double_first
    [1] * 2
  end
end

puts [1, 2, 3].double_first
Drag options to blanks, or click blank then click option'
Afirst()
Bself[0]
Cself.first
Dself[1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'self[1]' which accesses the second element.
Using 'first()' without 'self'.
4fill in blank
hard

Fill both blanks to reopen the Hash class and add a method that returns keys with values greater than 10.

Ruby
class Hash
  def keys_with_large_values
    select { |[1], [2]| [2] > 10 }.keys
  end
end

puts({a: 5, b: 15, c: 20}.keys_with_large_values)
Drag options to blanks, or click blank then click option'
Akey
Bvalue
Ck
Dv
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'key' and 'value' which are valid but not the correct answer here.
Mixing up the order of key and value.
5fill in blank
hard

Fill all three blanks to reopen the Numeric class and add a method that returns the number squared if positive, else zero.

Ruby
class Numeric
  def positive_square
    if [1] > 0
      [2] [3] 2
    else
      0
    end
  end
end

puts 4.positive_square
puts (-3).positive_square
Drag options to blanks, or click blank then click option'
Aself
C**
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using '*' instead of '**' for squaring.
Not using 'self' to refer to the number.