gsub with block

2168 views

What is the return value of the following Ruby code?

"aaoo".gsub("a") {|c| c.upcase} # => "AAoo"

"aaoo".gsub("a", "o") {|c| c.upcase} # => ???

The correct answer is

"AAOO"

"OOOO"

"oooo"

"AAAA"

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

In the given Ruby code, the gsub method is used to perform substitutions in a string.

Let's break down each line of code and explain the return values:

  1. "aaoo".gsub("a") { |c| c.upcase }: This line of code replaces each occurrence of the substring "a" in the original string "aaoo" with the result of the block provided, which converts the matched character c to its uppercase equivalent. In this case,"a" is replaced with "A", and the result is "AAoo".

  2. "aaoo".gsub("a", "o") { |c| c.upcase }: Similar to the first line, this code replaces each occurrence of the substring "a" in the original string "aaoo", but with the second argument "o" instead of a block. The block is still provided but is not used since a replacement string is given. Therefore, every "a" is replaced with "o", resulting in "oooo".

So, the return values for the two lines are as follows:

  1. The first line returns the string "AAoo".
  2. The second line returns the string "oooo".

Voilà!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©