summaryrefslogtreecommitdiff
path: root/spec/ruby/language/for_spec.rb
diff options
context:
space:
mode:
Diffstat (limited to 'spec/ruby/language/for_spec.rb')
-rw-r--r--spec/ruby/language/for_spec.rb103
1 files changed, 103 insertions, 0 deletions
diff --git a/spec/ruby/language/for_spec.rb b/spec/ruby/language/for_spec.rb
index 0ad5ea88af..b8ddfe5f0d 100644
--- a/spec/ruby/language/for_spec.rb
+++ b/spec/ruby/language/for_spec.rb
@@ -19,6 +19,27 @@ describe "The for expression" do
end
end
+ it "iterates over a list of arrays and destructures with an empty splat" do
+ for i, * in [[1,2]]
+ i.should == 1
+ end
+ end
+
+ it "iterates over a list of arrays and destructures with a splat" do
+ for i, *j in [[1,2]]
+ i.should == 1
+ j.should == [2]
+ end
+ end
+
+ it "iterates over a list of arrays and destructures with a splat and additional targets" do
+ for i, *j, k in [[1,2,3,4]]
+ i.should == 1
+ j.should == [2,3]
+ k.should == 4
+ end
+ end
+
it "iterates over an Hash passing each key-value pair to the block" do
k = 0
l = 0
@@ -81,6 +102,88 @@ describe "The for expression" do
end
end
+ it "allows a global variable as an iterator name" do
+ old_global_var = $var
+ m = [1,2,3]
+ n = 0
+ for $var in m
+ n += 1
+ end
+ $var.should == 3
+ n.should == 3
+ $var = old_global_var
+ end
+
+ it "allows an attribute as an iterator name" do
+ class OFor
+ attr_accessor :target
+ end
+
+ ofor = OFor.new
+ m = [1,2,3]
+ n = 0
+ for ofor.target in m
+ n += 1
+ end
+ ofor.target.should == 3
+ n.should == 3
+ end
+
+ # Segfault in MRI 3.3 and lower: https://bugs.ruby-lang.org/issues/20468
+ ruby_bug "#20468", ""..."3.4" do
+ it "allows an attribute with safe navigation as an iterator name" do
+ class OFor
+ attr_accessor :target
+ end
+
+ ofor = OFor.new
+ m = [1,2,3]
+ n = 0
+ eval <<~RUBY
+ for ofor&.target in m
+ n += 1
+ end
+ RUBY
+ ofor.target.should == 3
+ n.should == 3
+ end
+
+ it "allows an attribute with safe navigation on a nil base as an iterator name" do
+ ofor = nil
+ m = [1,2,3]
+ n = 0
+ eval <<~RUBY
+ for ofor&.target in m
+ n += 1
+ end
+ RUBY
+ ofor.should be_nil
+ n.should == 3
+ end
+ end
+
+ it "allows an array index writer as an iterator name" do
+ arr = [:a, :b, :c]
+ m = [1,2,3]
+ n = 0
+ for arr[1] in m
+ n += 1
+ end
+ arr.should == [:a, 3, :c]
+ n.should == 3
+ end
+
+ it "allows a hash index writer as an iterator name" do
+ hash = { a: 10, b: 20, c: 30 }
+ m = [1,2,3]
+ n = 0
+ for hash[:b] in m
+ n += 1
+ end
+ hash.should == { a: 10, b: 3, c: 30 }
+ n.should == 3
+ end
+
# 1.9 behaviour verified by nobu in
# http://redmine.ruby-lang.org/issues/show/2053
it "yields only as many values as there are arguments" do