mrubyを超漢字で動作させる
修訂 | e63c1e1d493bb97d4a299e2ab55c8aa6e46681e0 (tree) |
---|---|
時間 | 2014-01-10 21:49:57 |
作者 | Yukihiro "Matz" Matsumoto <matz@ruby...> |
Commiter | Yukihiro "Matz" Matsumoto |
Merge pull request #1655 from pbosetti/master
Added rewrite of Array#[] to mruby-array-ext gem
@@ -201,4 +201,36 @@ class Array | ||
201 | 201 | self.replace(result) |
202 | 202 | end |
203 | 203 | end |
204 | + | |
205 | + ## | |
206 | + # call-seq: | |
207 | + # ary[rng] -> ary slice | |
208 | + # | |
209 | + # Remeturns a slice of +ary+ according to the Range instance +rng+. | |
210 | + # | |
211 | + # a = [ "a", "b", "c", "d", "e" ] | |
212 | + # a[1] => "b" | |
213 | + # a[1,2] => ["b", "c"] | |
214 | + # a[1..-2] => ["b", "c", "d"] | |
215 | + # | |
216 | + def [](idx, len=nil) | |
217 | + case idx | |
218 | + when Range | |
219 | + if idx.last < 0 then | |
220 | + len = self.length - idx.first + idx.last + 1 | |
221 | + else | |
222 | + len = idx.last - idx.first + 1 | |
223 | + end | |
224 | + return self.slice(idx.first, len) | |
225 | + when Numeric | |
226 | + if len then | |
227 | + return self.slice(idx.to_i, len.to_i) | |
228 | + else | |
229 | + return self.slice(idx.to_i) | |
230 | + end | |
231 | + else | |
232 | + self.slice(idx) | |
233 | + end | |
234 | + end | |
235 | + | |
204 | 236 | end |
@@ -107,3 +107,10 @@ assert("Array#compact!") do | ||
107 | 107 | a.compact! |
108 | 108 | a == [1, "2", :t, false] |
109 | 109 | end |
110 | + | |
111 | +assert("Array#[]") do | |
112 | + a = [ "a", "b", "c", "d", "e" ] | |
113 | + a[1.1] == "b" and | |
114 | + a[1,2] == ["b", "c"] and | |
115 | + a[1..-2] == ["b", "c", "d"] | |
116 | +end |