Skip to content

Suggestion for inject #61

@jhaungs

Description

@jhaungs

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}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions