419 views
What is the return value of the following Ruby code?
words = [["abc", ["def"]], "ghi"] words[0][0][0][1] # => ???
The correct answer is
["def"]
"b"
"ghi"
nil
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
Let's detail what happens step-by-step
words = [["abc", ["def"]], "ghi"] words[0][0][0][1]
is equivalent to
words = [["abc", ["def"]], "ghi"] words[0] # => ["abc", ["def"]] words[0][0] # => "abc" words[0][0][0] # => "a" words[0][0][0][1] # => nil
In the original code, words[0][0][0][1]
attempts to access the second character of the single-character string "a"
using nested indexing.
However, since "a"
is a single-character string, trying to access the second character results in nil
being returned by String#[]
.
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©