0
0
Rubyprogramming~10 mins

Closures and variable binding 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 create a closure that returns a lambda adding a fixed number.

Ruby
def make_adder(n)
  return ->(x) { x [1] n }
end

add_five = make_adder(5)
puts add_five.call(10)
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting to use the lambda syntax.
2fill in blank
medium

Complete the code to capture the variable correctly inside the closure.

Ruby
def make_multipliers
  multipliers = []
  3.times do |i|
    multipliers << ->(x) { x * [1] }
  end
  multipliers
end

procs = make_multipliers
puts procs[0].call(2)
Drag options to blanks, or click blank then click option'
A2
B3
Cx
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed number instead of the loop variable.
Using the wrong variable name.
3fill in blank
hard

Fix the error in the closure to correctly capture the loop variable value.

Ruby
def make_procs
  procs = []
  3.times do |i|
    val = i
    procs << -> { val [1] 1 }
  end
  procs
end

procs = make_procs
puts procs[1].call
Drag options to blanks, or click blank then click option'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Not capturing the variable correctly.
4fill in blank
hard

Fill both blanks to create a closure that captures the current loop variable and multiplies it.

Ruby
def make_funcs
  funcs = []
  4.times do |i|
    funcs << ->(x) { (x [1] i) [2] 2 }
  end
  funcs
end

funcs = make_funcs
puts funcs[2].call(3)
Drag options to blanks, or click blank then click option'
A*
B+
C**
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of addition.
Using subtraction instead of exponentiation.
5fill in blank
hard

Fill all three blanks to create a closure that filters and transforms a hash based on variable binding.

Ruby
def filter_transform(data)
  result = data.select { |k, v| v [1] 10 }
               .map { |k, v| [k.[2], v [3] 5] }
  result.to_h
end

input = {"a" => 12, "b" => 8, "c" => 15}
output = filter_transform(input)
puts output
Drag options to blanks, or click blank then click option'
A>
Bupcase
C-
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than instead of greater than for filtering.
Not transforming keys or values correctly.