Skip to content

Commit 94f393c

Browse files
committed
[Truffle] Pulled in String#lines from Rubinius.
1 parent 50d2b70 commit 94f393c

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

truffle/src/main/java/org/jruby/truffle/nodes/core/StringNodes.java

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -741,7 +741,7 @@ public RubyString eachChar(VirtualFrame frame, RubyString string, RubyProc block
741741

742742
}
743743

744-
@CoreMethod(names = "each_line")
744+
@CoreMethod(names = "each_line", optional = 1)
745745
public abstract static class EachLineNode extends YieldingCoreMethodNode {
746746

747747
public EachLineNode(RubyContext context, SourceSection sourceSection) {
@@ -753,31 +753,41 @@ public EachLineNode(EachLineNode prev) {
753753
}
754754

755755
@Specialization
756-
public RubyArray eachLine(RubyString string) {
756+
public RubyArray eachLine(RubyString string, @SuppressWarnings("unused") UndefinedPlaceholder separator) {
757+
notDesignedForCompilation();
758+
759+
final RubyBasicObject globals = getContext().getCoreLibrary().getGlobalVariablesObject();
760+
final RubyString recordSeparator = (RubyString) globals.getInstanceVariable("$/");
761+
return eachLine(string, recordSeparator);
762+
}
763+
764+
@Specialization
765+
public RubyArray eachLine(RubyString string, RubyString separator) {
757766
notDesignedForCompilation();
758767

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

761770
String str = string.toString();
771+
String sep = separator.toString();
772+
762773
int start = 0;
763774

764775
while (start < str.length()) {
765-
int end = str.indexOf('\n', start);
776+
int end = str.indexOf(sep, start);
766777

767778
if (end == -1) {
768779
lines.add(getContext().makeString(str.substring(start)));
769780
break;
770781
}
771782

772-
String line = str.substring(start, end+1);
773-
start = end+1;
783+
String line = str.substring(start, end + sep.length());
784+
start = end + sep.length();
774785

775786
lines.add(getContext().makeString(line));
776787
}
777788

778789
return RubyArray.fromObjects(getContext().getCoreLibrary().getArrayClass(), lines.toArray(new Object[lines.size()]));
779790
}
780-
781791
}
782792

783793
@CoreMethod(names = "empty?")

truffle/src/main/ruby/jruby/truffle/core/rubinius/kernel/common/string.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,16 @@ def chomp(separator=$/)
4747
str.chomp!(separator) || str
4848
end
4949

50+
def lines(sep=$/)
51+
if block_given?
52+
each_line(sep) do |line|
53+
yield line
54+
end
55+
else
56+
each_line(sep).to_a
57+
end
58+
end
59+
5060
def start_with?(*prefixes)
5161
prefixes.each do |original_prefix|
5262
prefix = Rubinius::Type.check_convert_type original_prefix, String, :to_str

0 commit comments

Comments
 (0)