From ff5da5041b9b958af8299e90173dc7bf568b0181 Mon Sep 17 00:00:00 2001 From: gogotanaka Date: Wed, 29 Oct 2014 00:31:54 -0700 Subject: [PATCH 1/3] Improve for Vector#[] --- lib/matrix.rb | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/lib/matrix.rb b/lib/matrix.rb index f7d75b3..6c13488 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -1685,7 +1685,7 @@ end # * Vector.basis(size: n, index: k) # # To access elements: -# * #[](i) +# * #[](arg) # # To enumerate the elements: # * #each2(v) @@ -1770,10 +1770,24 @@ class Vector # ACCESSING # - # Returns element number +i+ (starting at zero) of the vector. + # :call-seq: + # vector[index] -> obj or nil + # vector[range] -> new_vector or nil + # + # Element Assignment — the element at index or + # replaces a new vector specified by the range of indices. + # + # Vector[1, 2, 3][1] + # => 2 + # + # Vector[1, 2, 3][1..-1] + # => Vector[2, 3] + # + # Like Array#[], Negative indices will count backward from the end of the vector. # - def [](i) - @elements[i] + def [](arg) + return unless elements = @elements[arg] + arg.is_a?(Range) ? Vector[*elements] : elements end alias element [] alias component [] -- 1.8.5.2 (Apple Git-48)