Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion for inject #61

Open
jhaungs opened this issue May 26, 2016 · 1 comment
Open

Suggestion for inject #61

jhaungs opened this issue May 26, 2016 · 1 comment

Comments

@jhaungs
Copy link

jhaungs commented May 26, 2016

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}
@franzejr
Copy link
Owner

@jhaungs, look at this: #60

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants