Skip to content

Commit

Permalink
Showing 2 changed files with 26 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -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) {
@@ -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?")
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 94f393c

Please sign in to comment.