[#104004] [Ruby master Feature#17883] Load bundler/setup earlier to make `bundle exec ruby -r` respect Gemfile — mame@...
Issue #17883 has been reported by mame (Yusuke Endoh).
21 messages
2021/05/24
[ruby-core:103753] [Ruby master Feature#17844] Support list of methods to test with respond_to?
From:
svoop_he38hj327c@...
Date:
2021-05-06 07:22:27 UTC
List:
ruby-core #103753
Issue #17844 has been updated by svoop (Sven Schwyn).
Fair point, but I don't think `respond_to_any?` is a real use case given `respond_to?` is mostly used to check whether an object implements the necessary interface: The information "it implements method1 OR method2" has little practical value.
Also, the predominant assumption made by other methods accepting one or many args appears to be AND (additive):
* `Array#push`
* `Array#union`
* `Hash#slice`
* (many more)
TL;DR It should not be a surprise for `respond_to?(:email, :name)` to returns `true` if and only if both methods are implemented on the receiver.
----------------------------------------
Feature #17844: Support list of methods to test with respond_to?
https://bugs.ruby-lang.org/issues/17844#change-91859
* Author: svoop (Sven Schwyn)
* Status: Open
* Priority: Normal
----------------------------------------
Not sure whether this is a good idea at all, but I guess it doesn't hurt to put it up for debate.
The preferred way to check e.g. whether an argument is acceptable is by use of `respond_to?`:
```ruby
# Don't
def notify(recipient)
raise ArgumentError unless recipient.instance_of?(User) || recipient.instance_of?(Follower)
...
end
# Do
def notify(recipient)
raise ArgumentError unless recipient.respond_to? :email
...
end
```
However, sometimes the tested object has to respond to more than one method in order to be acceptable:
```ruby
def notify(recipient)
raise ArgumentError unless recipient.respond_to?(:email) && recipient.respond_to?(:name)
...
end
```
The refactored version doesn't look much nicer:
```ruby
def notify(recipient)
raise ArgumentError unless %i(email name).reduce(true) do |memo, method|
memo &&= recipient.respond_to? method
end
...
```
The limiting factor here is `respond_to?` which only accepts one method as String or Symbol. How about extending it to accept an Array (of String or Symbol) as well?
```ruby
def notify(recipient)
raise ArgumentError unless recipient.respond_to? %i(email name)
...
```
Even nicer, but more complicated to implement due to the last and optional argument `include_all`:
```ruby
def notify(recipient)
raise ArgumentError unless recipient.respond_to?(:email, :name)
...
```
What do you think?
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>