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:
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
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 valueA 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).”
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.