Skip to content

Commit

Permalink
[Truffle] Pulled in String#lines from Rubinius.
Browse files Browse the repository at this point in the history
  • Loading branch information
nirvdrum committed Feb 6, 2015
1 parent 50d2b70 commit 94f393c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
Expand Up @@ -741,7 +741,7 @@ public RubyString eachChar(VirtualFrame frame, RubyString string, RubyProc block

}

@CoreMethod(names = "each_line")
@CoreMethod(names = "each_line", optional = 1)
public abstract static class EachLineNode extends YieldingCoreMethodNode {

public EachLineNode(RubyContext context, SourceSection sourceSection) {
Expand All @@ -753,31 +753,41 @@ public EachLineNode(EachLineNode prev) {
}

@Specialization
public RubyArray eachLine(RubyString string) {
public RubyArray eachLine(RubyString string, @SuppressWarnings("unused") UndefinedPlaceholder separator) {
notDesignedForCompilation();

final RubyBasicObject globals = getContext().getCoreLibrary().getGlobalVariablesObject();
final RubyString recordSeparator = (RubyString) globals.getInstanceVariable("$/");
return eachLine(string, recordSeparator);
}

@Specialization
public RubyArray eachLine(RubyString string, RubyString separator) {
notDesignedForCompilation();

final List<Object> lines = new ArrayList<>();

String str = string.toString();
String sep = separator.toString();

int start = 0;

while (start < str.length()) {
int end = str.indexOf('\n', start);
int end = str.indexOf(sep, start);

if (end == -1) {
lines.add(getContext().makeString(str.substring(start)));
break;
}

String line = str.substring(start, end+1);
start = end+1;
String line = str.substring(start, end + sep.length());
start = end + sep.length();

lines.add(getContext().makeString(line));
}

return RubyArray.fromObjects(getContext().getCoreLibrary().getArrayClass(), lines.toArray(new Object[lines.size()]));
}

}

@CoreMethod(names = "empty?")
Expand Down
Expand Up @@ -47,6 +47,16 @@ def chomp(separator=$/)
str.chomp!(separator) || str
end

def lines(sep=$/)
if block_given?
each_line(sep) do |line|
yield line
end
else
each_line(sep).to_a
end
end

def start_with?(*prefixes)
prefixes.each do |original_prefix|
prefix = Rubinius::Type.check_convert_type original_prefix, String, :to_str
Expand Down

0 comments on commit 94f393c

Please sign in to comment.