3 ms·
ruby has the convention of ! for dangerous destructive or mutating methods. This is something that I wish would spread around a bit. For example: # Original a
by ecshafer 7mo ago
ruby has the convention of ! for dangerous destructive or mutating methods. This is something that I wish would spread around a bit.
For example:
# Original array
array = [1, 2, 3]
# Using map (non-destructive)
new_array = array.map { |x| x * 2 }
# new_array is [2, 4, 6]
# array is still [1, 2, 3] (unchanged)
# Using map! (destructive)
array.map! { |x| x * 2 }
# array is now [2, 4, 6] (modified in-place)
- wiseowise 7mo ago> convention Is the keyword. Anything that should never be broken isn’t a convention. There’s no better convention than compiler error.
- goatlover 7mo agoBecause Ruby is a dynamic language which mutates state. That isn't considered wrong or bad in those kinds of languages, just a way to make sure the programmer knows they're doing that. Not every PL tries to live up to the ideals of Haskell. If you don't want an object mutated in Ruby, you can freeze it.
- idle_zealot 7mo agoI don't think they're saying it shouldn't be possible to mutate arguments, just that the ! convention should be enforced. The Ruby runtime could, for instance, automatically freeze all arguments to a function that doesn't end with a !. That way all code that correctly follows the mutation naming convention will continue to work, and any development who doesn't know about it will quickly learn when they try to mutate an argument and get an error. Ideally a helpful error telling them to add the !.
- xp84 7mo agoThat's really interesting. Although my worry is the freezing having bad effects down the line after the function returns. a = [1, 2] def check_this(arr) raise "doesn't start with 1" unless a.first == 1 end check_this(a) a << 3 # Raises "FrozenError (can't modify frozen Array)" because check_this froze `a` Now, if you could temporarily freeze, and then unfreeze only the ones you froze, that could be really cool.
- idle_zealot 7mo ago> Now, if you could temporarily freeze, and then unfreeze only the ones you froze, that could be really cool. Is that a missing feature in Ruby? You can't have a frozen reference to an object while retaining unfrozen ones in another scope? That's too bad.
- xp84 7mo agoYeah, in my testing freeze mutates the object itself to a permanent frozen state.