// @RubyLevelMethod(name="[]", alias="slice") public RubyValue aref(RubyValue arg) { if (arg instanceof RubyFixnum) { return this.get(arg.toInt()); } if (arg instanceof RubySymbol) { throw new RubyException(RubyRuntime.TypeErrorClass, "Symbol as array index"); } if (arg instanceof RubyRange) { RubyRange range = (RubyRange) arg; int begin = range.getLeft().toInt(); int end = range.getRight().toInt(); if (begin < 0) { begin = this.size() + begin; } if (end < 0) { end = this.size() + end; } if (!range.isExcludeEnd()) { ++end; } RubyArray resultValue = this.subarray(begin, end - begin); if (null == resultValue) return RubyConstant.QNIL; return resultValue; // return (null == resultValue ? RubyConstant.QNIL : resultValue); } return this.get(arg.toInt()); }
// @RubyLevelMethod(name="[]") public RubyValue array_access(RubyArray args) { String string = toString(); if (args.size() == 1) { RubyValue arg = args.get(0); if (arg instanceof RubyString) { String str = ((RubyString) arg).toString(); if (string.indexOf(str) >= 0) { return ObjectFactory.createString(str); } else { return RubyConstant.QNIL; } } else if (arg instanceof RubyRange) { RubyRange range = (RubyRange) arg; int start = range.getLeft().toInt(); int end = range.getRight().toInt(); return substring(string, start, end, range.isExcludeEnd()); } else if (arg instanceof RubyRegexp) { RubyRegexp regexp = (RubyRegexp) arg; RubyMatchData match = regexp.match(string); if (match != null) { return ObjectFactory.createString(match.toString()); } else { return RubyConstant.QNIL; } } else { int index = arg.toInt(); if (index < 0) { index = string.length() + index; } if (index < 0 || index >= string.length()) { return RubyConstant.QNIL; } else { return ObjectFactory.createFixnum(string.charAt(index)); } } } else { int start = args.get(0).toInt(); int length = args.get(1).toInt() - 1; return substring(string, start, start + length, false); } }