rails icon indicating copy to clipboard operation
rails copied to clipboard

Add clarification in the explanation of index_with variants

Open dsusviela opened this issue 1 year ago • 3 comments

Summary

Documentation clarification regarding the index_with method. Product of the discussion over at #45286

dsusviela avatar Jun 07 '22 17:06 dsusviela

I agree adding a clarification seems helpful, though I am wary that this weights the bulk of the method description to the already-unusual case of a non-block argument 🤔

I wonder if we can avoid the example by leaning on a more explicit parallel to other Hash behaviours that do the same thing, like a non-block default, and thereby keep it to just a sentence?

Even the existing example didn't ring particularly true for me as a frequently-encounterable usage pattern... really the only non-block values I'd expect to regularly see here are true, false, nil, and at the outside, 0 or 1 (though tally is likely a better way to get the latter result).

matthewd avatar Jun 10 '22 14:06 matthewd

@matthewd What would you suggest to avoid weighing too much of the bulk of the description into that use case? I think we could remove the last sentence "If this is not desired, use the block variant instead." as that's pretty much a given. I agree with you that compared to other methods in this same doc page, this proposition can get it to be too verbose.

However I do see the value in the example for this case. In the Hash,new(["value"]) case I think you can get away with not going too deep into the matter because it's kind of expected that the fallback value changes if I change the variable as its the only intuitive way of achieving this:

names = ["ruby"]
languages = Hash.new(names) # languages = {} <- hash is empty

languages[:awesome]  # ["ruby"]

names << "elixir"
languages[:awesome] # ["ruby", "elixir"] <- i changed the default so i expected this

Granted, you can do the following

names = ["ruby"]
languages = Hash.new(names) # languages = {} <- hash is empty

languages[:awesome]  << "elixir"
languages[:awesome] # ["ruby", "elixir"], the hash is still empty

But its not intuitive because the hash does not really contain that key.

When doing index_with I'm not passing in a fallback value but a value for the resulting hash.

names = ["ruby"]
languages = [:awesome].index_with(names) # { :awesome => ["ruby"] }

languages[:boring] # nil <- the array is not the fallback

Therefore changing the value under one of the keys for the resulting hash of index_with is not something I would call surprising. Specially if the dev is inexperienced in the intricacies of ruby/rails and sees the argument variant as the "simple form" of calling the method.

dsusviela avatar Jun 10 '22 15:06 dsusviela

Hey @matthewd have you had the chance to review my message?

dsusviela avatar Aug 04 '22 16:08 dsusviela