You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In "Idiomatic Ruby / Combine..." the first statement is extraneous.
hash = {} # not needed, even misleading
values.inject({}) do |hash, value|
hash.merge(value => value ** 2)
end
In older versions of ruby, the hash var would collide with the block arg; in modern ruby, they're scoped, so the hash being injected is the {} arg to inject, not the variable.
A more idiomatic version might be:
result = values.inject({}) do |hash, value|
hash.merge(value => value ** 2)
end
It would also be useful to note that the use of merge with inject is a bit tricky, and only works because merge returns the hash itself. If the last expression in the block doesn't return the injected value, the inject will fail in weird ways. A less error-prone way to code it is to always return the injected value:
result = values.inject({}) do |hash, value|
hash[value] = value ** 2
hash
end
or, as a one-liner:
result = values.inject({}) {|hash, value| hash[value] = value ** 2; hash}
The text was updated successfully, but these errors were encountered:
In "Idiomatic Ruby / Combine..." the first statement is extraneous.
In older versions of ruby, the hash var would collide with the block arg; in modern ruby, they're scoped, so the hash being injected is the {} arg to inject, not the variable.
A more idiomatic version might be:
It would also be useful to note that the use of merge with inject is a bit tricky, and only works because merge returns the hash itself. If the last expression in the block doesn't return the injected value, the inject will fail in weird ways. A less error-prone way to code it is to always return the injected value:
or, as a one-liner:
The text was updated successfully, but these errors were encountered: