Bug #16086
closedOpenStruct method access with a block does not raise
Description
This can cause confusion.
> OpenStruct.new(hello: 'world').each { |k, v| puts k.upcase } # there's no "each" method
=> nil
> OpenStruct.new(hello: 'world').eahc_pair { |k, v| puts k.upcase } # each_pair typo
=> nil
An undefined key with a block should maybe raise NoMethodError
or ArgumentError
?
A defined key with a block seems to yield the value, I don't see this being documented:
> OpenStruct.new(hello: 'world').hello { |k| puts k.upcase }
HELLO
Maybe it should raise ArgumentError
too?
Updated by nobu (Nobuyoshi Nakada) about 5 years ago
- Status changed from Open to Feedback
kke (Kimmo Lehto) wrote:
This can cause confusion.
> OpenStruct.new(hello: 'world').each { |k, v| puts k.upcase } # there's no "each" method => nil > OpenStruct.new(hello: 'world').eahc_pair { |k, v| puts k.upcase } # each_pair typo => nil
An undefined key with a block should maybe raise
NoMethodError
orArgumentError
?
That is OpenStruct
, an undefined key does not raise an exception.
And an unused block is silently ignored in common.
A defined key with a block seems to yield the value, I don't see this being documented:
> OpenStruct.new(hello: 'world').hello { |k| puts k.upcase } HELLO
Maybe it should raise
ArgumentError
too?
I haven't seen such behavior.
$ ruby -rostruct -e 'p OpenStruct.new(hello: "world").hello { |k| puts k.upcase }'
"world"
Updated by kke (Kimmo Lehto) about 5 years ago
That is OpenStruct, an undefined key does not raise an exception.
And an unused block is silently ignored in common.
Right, this behavior seems to be universal:
> { foo: :bar }[:foo] { 'hello' }
=> :bar
> 1.abs { 'hello' }
=> 1
I haven't seen such behavior.
$ ruby -rostruct -e 'p OpenStruct.new(hello: "world").hello { |k| puts k.upcase }' "world"
Hmm, I can't replicate it anymore either. I must have been experimenting with each_pair
.
I guess nothing in this issue is actually an issue and it can be closed. This came from frustration when I assumed there was an each
method and all I got was nil
and couldn't figure out why.
Updated by kke (Kimmo Lehto) about 5 years ago
- Status changed from Feedback to Closed