简体   繁体   中英

Destructuring arguments to comparison operators

Edited question: Does the Ruby syntax allow destructuring of Arrays in a nice way when using comparison operators?

Original question: Does the Ruby syntax allow destructuring of Arrays in a nice way?

For method calls one can use the Splat operator (*), but is it possible to do this without calling a method?

This is allowed:

foo = ['bar']
'bar'.==(*foo) # => true

Can this be written more similarly to this?

'bar' == *foo
# => *** SyntaxError Exception: (byebug):1: syntax error, unexpected *
# => 'bar' == *foo

Edit: The question arose from code looking a little like this:

assert('test@example.com' == *email.to) # => Syntax error
assert_equal('test@example.com', *email.to) # => Success
foo, = ['bar']
#⇒ ["bar"]
foo
#⇒ "bar"

There might be as many variables as needed.

foo, bar, *baz = %w|foo bar baz|
foo
#⇒ "foo"
bar
#⇒ "bar"
baz
#⇒ ["baz"]

The reason 'bar' == *foo doesn't work is because the parser expects exactly one parameter for most operators (including the comparison operator). In the case of 'bar'.==(*foo) the method still expects one parameter, but the parser doesn't see a problem, since you called it using a normal method call. To resolve this you could just call #first on the array: 'bar' == foo.first


The reason this works for #assert_equal is because elements of the email.to array are send as parameters.

However, if the array is empty you will get an argument error:

ArgumentError: wrong number of arguments (given 1, expected 2..3)

If the array contains more than 2 elements you will get the error:

ArgumentError: wrong number of arguments (given 4, expected 2..3)

If the array contains 2 elements the second element is used as error message in case of failure.

In conclusion you will only get the wanted result if the array contains exactly one element. This raises the question "Why use an array in the first place?" You could just use a normal variable, there is no reason to wrap it in an array (in the given context).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM