shou2017.com
JP

Ruby Exam: Built-in Library (Array)

Sun May 6, 2018
Sat Aug 10, 2024

Array-related questions frequently appear in the Ruby Silver exam.

I often get confused, so here’s a note.

These types of questions are commonly asked:

From [Revised 2nd Edition] Ruby Certification Exam Study Guide (Silver/Gold) Official Ruby Certification Textbook

Question

Choose the appropriate code to write in X so that the following output is achieved. (Select two options)

a = [ 1, 2, 3, 4]
x.each do |i| print i, " " end

<!-- Output -->

1 2 3

Answer

  • a[0..-2]
  • a[0,3]

Explanation for a[0..-2]

This is a common array subscript operator [ ] question in the Silver exam.

Negative indices in arrays specify elements in reverse order from the last element. The last element is -1, and - represents the count of elements in the array.

For this problem:

In a = [ 1, 2, 3, 4], the element 4 corresponds to -1. To achieve the output 1 2 3, the correct range is from 0 to -2.

# Elements
     -4 -3 -2  -1
a = [ 1, 2, 3, 4]

# Try referencing 1
irb > p [-4]
=> 1

Additionally, there’s a trick in this question: the difference between .. and ... in ranges. The difference is whether the right-side value is included or not.

  • .. includes the value
  • ... excludes the value

A mnemonic: .. has two dots, so it “includes”; ... has more than two dots, so it “excludes.”

Thus, a[0..-2] can be interpreted as “from the 0th element to the -2nd element (inclusive).”

Explanation for a[0,3]

This is straightforward.

The comma specifies the number of elements from a certain position in the array. In this case, it references three elements starting from the 0th position.

[改訂2版]Ruby技術者認定試験合格教本

See Also