Project

General

Profile

Bug #12104

Procs keyword arguments affect value of previous argument

Added by cheerfulstoic (Brian Underwood) about 1 year ago. Updated about 1 year ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
ruby -v:
Tested in 2.3.0 and 2.2.3
[ruby-core:73949]

Description

This seems like a bug to me:

2.3.0 :001 > p = Proc.new {|nodes, match_array: false| puts nodes.inspect }
 => #<Proc:0x007fa52c0659e0@(irb):1>
2.3.0 :002 > p.call([])
nil
 => nil
2.3.0 :003 >  p.call([], match_array: true)
[]
 => nil

When I try the same thing in a method I get the behavior I would expect:

2.3.0 :004 > def foo(nodes, match_array: false)
2.3.0 :005?>   puts nodes.inspect
2.3.0 :006?>   end
 => :foo
2.3.0 :007 > foo([])
[]
 => nil
2.3.0 :008 > foo([], match_array: true)
[]

History

#1 [ruby-core:73950] Updated by cheerfulstoic (Brian Underwood) about 1 year ago

This seems to also happen when trying to use a options Hash as the second argument:

2.3.0 :009 > p = Proc.new {|nodes, options = {}| puts nodes.inspect }
 => #<Proc:0x007fa52b13b348@(irb):9>
2.3.0 :010 > p.call([])
nil
 => nil
2.3.0 :011 > p.call([], match_array: true)
[]

#2 [ruby-core:73951] Updated by cheerfulstoic (Brian Underwood) about 1 year ago

Looking deeper now it seems to be that this is because the first argument is an Array and that when that happens it's interpreting that as the elements of the array being the arguments of the Proc. Is that supposed to happen?

#3 [ruby-core:74374] Updated by ko1 (Koichi Sasada) about 1 year ago

  • Status changed from Open to Rejected

You are right.
It is intentional.

#4 [ruby-core:74382] Updated by znz (Kazuhiro NISHIYAMA) about 1 year ago

How about using lambda instead of Proc.new?

>> p = lambda {|nodes, match_array: false| puts nodes.inspect }
=> #<Proc:0x0000000183a0a8@(irb):1 (lambda)>
>> p.call([])
[]
=> nil
>> p = lambda {|nodes, options = {}| puts nodes.inspect }
=> #<Proc:0x00000001850c68@(irb):3 (lambda)>
>> p.call([])
[]
=> nil

Also available in: Atom PDF