Project

General

Profile

Actions

Feature #16295

closed

Chainable aliases for String#-@ and String#+@

Added by byroot (Jean Boussier) over 4 years ago. Updated about 2 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:95702]

Description

Original discussion https://bugs.ruby-lang.org/issues/16150?next_issue_id=16147&prev_issue_id=16153#note-40

In #16150, @headius (Charles Nutter) raised the following concern about String#-@ and String#+@:

headius (Charles Nutter) wrote:

Not exactly, -@ and +@ makes this much simpler

I do like the unary operators, but they also have some precedence oddities:

>> -"foo".size
=> -3
>> (-"foo").size
=> 3

And it doesn't work at all if you're chaining method calls:

>> +ary.to_s.frozen?
NoMethodError: undefined method `+@' for false:FalseClass
	from (irb):8
	from /usr/bin/irb:11:in `<main>'

But you are right, instead of the explicit dup with possible freeze you could use - or + on the result of to_s. However it's still not safe to modify it since it would modify the original string too.

After working for quite a while with those, I have to say I agree. They very often force to use parentheses, which is annoying, and an indication that regular methods would be preferable to unary operators.

In response @matz (Yukihiro Matsumoto) proposed to alias them as String#+ and String#- without arguments:

How about making String#+ and #- without argument behave like #+@ and #-@ respectively, so that we can write:

"foo".-.size
ary.to_s.+.frozen?

My personal opinion is that descriptive method names would be preferable to +/-:

IMHO .- and .+ is not very elegant. Proper method names explaining the intent would be preferable.

  • -@ could be dedup, or deduplicate.
  • +@ could be mutable or mut.

Related issues 2 (1 open1 closed)

Related to Ruby master - Feature #18595: Alias `String#-@` as `String#dedup`ClosedActions
Related to Ruby master - Feature #18597: Strings need a named method like `dup` that doesn't duplicate if receiver is mutableOpenActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0