예제 #1
0
  // @RubyLevelMethod(name="split")
  public RubyValue split(RubyArray args) {
    RubyValue r = (null == args) ? GlobalVariables.get("$;") : args.get(0);

    Collection /*<String>*/ splitResult;
    boolean bSkipFirstEmptyItem = false;
    if (r == RubyConstant.QNIL) {
      splitResult = split(this, " ");
    } else if (r instanceof RubyRegexp) {
      RubyRegexp reg = (RubyRegexp) r;
      splitResult = split(this, reg, args);

      if (reg.getPattern().getPattern().startsWith("(?=")) bSkipFirstEmptyItem = true;
    } else if (r instanceof RubyString) {
      splitResult = split(this, ((RubyString) r).toString());
    } else {
      throw new RubyException(
          RubyRuntime.ArgumentErrorClass,
          "wrong argument type " + r.getRubyClass() + " (expected Regexp)");
    }

    RubyArray a = new RubyArray(splitResult.size());
    int i = 0;
    //        for (String str : splitResult) {
    for (Iterator iter = splitResult.iterator(); iter.hasNext(); ) {
      String str = (String) iter.next();
      if (!(bSkipFirstEmptyItem && 0 == i && (str == null || str.equals("")))) {
        // To conform ruby's behavior, discard the first empty element
        a.add(ObjectFactory.createString(str));
      }
      ++i;
    }
    return a;
  }
예제 #2
0
  private Collection /*<String>*/ split(RubyString s, String delimiter) {
    StringParser t = new StringParser(s.toString(), delimiter);
    //        int total = t.countTokens();
    // Collection/*<String>*/ r = new ArrayList/*<String>*/(total);
    //        for (int i = 0; i < total; ++i) {
    //            r.add(t.nextToken());
    //        }

    Collection /*<String>*/ r = new ArrayList /*<String>*/(0);
    while (t.hasMoreElements()) {
      r.add(t.nextElement());
    }
    return r;
  }