From: "rubyFeedback (robert heiler) via ruby-core" Date: 2023-02-17T08:48:17+00:00 Subject: [ruby-core:112469] [Ruby master Feature#18597] Strings need a named method like `dup` that doesn't duplicate if receiver is mutable Issue #18597 has been updated by rubyFeedback (robert heiler). > And it feels like I cannot convince anyone here with any amount of rationale Ultimately you only have to convince matz, so you could ignore what others write. But one reason why there was a reference to real-needs is that the ruby core/dev team said that they focus on real needs (although they may evaluate what is real and what is not ultimately, as well as the cost of addition of methods). My personal opinion is that, usage aside, the .dup_if_immutable feels very clunky. The simplest variant is of course the oldschool ruby: string_object << "More content." I use this pattern, which is a bit verbose: string_object = string_object.dup if string_object.frozen? Then there is that +@ variant. I avoid it, but I guess one reason why it is used is because it is quite short. From a user's perspective, the << usage in oldschool ruby before frozen string is the most convenient, but the primary reason why it was changed was due to speed/efficiency. And other languages such as python have immutable strings too so it's a real concern. ---------------------------------------- Feature #18597: Strings need a named method like `dup` that doesn't duplicate if receiver is mutable https://bugs.ruby-lang.org/issues/18597#change-101914 * Author: danh337 (Dan H) * Status: Open * Priority: Normal ---------------------------------------- This is related to #16295, but focuses only on the `.+@` part. Currently we can use `.dup` in a method chain when we need to mutate a String. However there are cases where the code's context *expects* the String to be mutated. In cases like this, `.dup` always works, but we don't want to duplicate a String that is already mutable. Since `.+@` looks more like an operator, it can be unintuitive in a method chain, so this is asking for a new named method that can be used in its place, instead of always `.dup`. For example: ``` def add_result_text(buffer, new_result) text = "#{new_result.count} #{new_result.input} #{do_fancy_calc(new_result)}\n" buffer.dup_if_immutable << text # ^^^^^^^^^^^^^^^^ new method? end buffer = "" # ...maybe immutable get_lots_of_results.each do |result| buffer = add_result_text(buffer, result) # In case it was dup'ed end ``` ---Files-------------------------------- driver.rb (12.3 KB) driver.rb (12.7 KB) -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/