Rails: difference between ENV.fetch() and ENV[]
Asked Answered
C

1

75

What is the difference between these two syntax:

ENV.fetch("MY_VAR")

ENV['MY_VAR']

I've seen Rails 5 use both versions of these in difference places and can't figure out what the difference is (apart from the first one being more characters to type).

Citreous answered 27/12, 2017 at 2:32 Comment(1)
@JörgWMittag It is pretty clear to everyone else what they're asking, not everyone consults a dictionary when asking a question. You're welcome to provide your own answer if you need to display your command of the English language.Bashan
B
128

The ENV hash-like object is plain Ruby, not part of Rails. From the fine ENV#[] manual:

Retrieves the value for environment variable name as a String. Returns nil if the named variable does not exist.

and the fine ENV#fetch manual:

Retrieves the environment variable name.

If the given name does not exist and neither default nor a block a provided an IndexError is raised. If a block is given it is called with the missing name to provide a value. If a default value is given it will be returned when no block is given.

So just like Hash#[] and Hash#fetch, the only difference is that fetch allows you to specify the behavior if a key is not found (use a default value passed to fetch, default block passed to fetch, or raise an exception) whereas [] just silently gives you nil if the key isn't found.

In the specific case of:

ENV.fetch("MY_VAR")
ENV['MY_VAR']

the difference is that ENV['MY_VAR'] will give you nil if there is no MY_VAR environment variable but ENV.fetch('MY_VAR') will raise an exception.

Bashan answered 27/12, 2017 at 2:51 Comment(3)
This is how the default value is used: ENV.fetch('NON_EXISTENT') {'returns this string'}Combo
or ENV.fetch('NON_EXISTENT', 'my default value') @ComboEnwomb
@YannickSchuchmann indeed! My example should have been ENV.fetch('NON_EXISTENT') { <compute the value> } or something more appropriate for a block. Otherwise the second parameter in you comment is much better.Combo

© 2022 - 2024 — McMap. All rights reserved.