Check for Ruby env variable [duplicate] - ruby

In Ruby, I am trying to write a line that uses a variable if it has been set, otherwise default to some value:
myvar = # assign it to ENV['MY_VAR'], otherwise assign it to 'foobar'
I could write this code like this:
if ENV['MY_VAR'].is_set? #whatever the function is to check if has been set
myvar = ENV['MY_VAR']
else
myvar = 'foobar'
end
But this is rather verbose, and I'm trying to write it in the most concise way possible. How can I do this?

myvar = ENV['MY_VAR'] || 'foobar'
N.B. This is slightly incorrect (if the hash can contain the value nil) but since ENV contains just strings it is probably good enough.

The most reliable way for a general Hash is to ask if it has the key:
myvar = h.has_key?('MY_VAR') ? h['MY_VAR'] : 'default'
If you don't care about nil or false values (i.e. you want to treat them the same as "not there"), then undur_gongor's approach is good (this should also be fine when h is ENV):
myvar = h['MY_VAR'] || 'foobar'
And if you want to allow nil to be in your Hash but pretend it isn't there (i.e. a nil value is the same as "not there") while allowing a false in your Hash:
myvar = h['MY_VAR'].nil? ? 'foobar' : h['MY_VAR']
In the end it really depends on your precise intent and you should choose the approach that matches your intent. The choice between if/else/end and ? : is, of course, a matter of taste and "concise" doesn't mean "least number of characters" so feel free to use a ternary or if block as desired.

hash.fetch(key) { default_value }
Will return the value if it exists, and return default_value if the key doesn't exist.

This works best for me:
ENV.fetch('VAR_NAME',"5445")

myvar = ENV.fetch('MY_VAR') { 'foobar' }
'foobar' being the default if ENV['MY_VAR'] is unset.

Although it's not relevant in the specific example you gave since you're really asking about hash keys, not variables, Ruby does give a way to check variable definition. Use the defined? keyword (it's not a method, but a keyword since it needs special handling by the interpreter), like so:
a = 1
defined? a
#=> "local-variable"
#a = 2
defined? #a
#=> "instance-variable"
##a = 3
defined? ##a
#=> "class-variable"
defined? blahblahblah
#=> nil
Hence you could do:
var = defined?(var) ? var : "default value here"
As far as I know, that's the only way other than an ugly begin/rescue/end block to define a variable in the way that you ask without risking a NameError. As I said, this doesn't apply to hashes since:
hash = {?a => 2, ?b => 3}
defined? hash[?c]
#=> "method"
i.e. you're checking that the method [] is defined rather than the key/value pair you're using it to access.

Another possible alternative, which will work even if ENV['MY_VAR'] turnsout to be a false value
myvar = ENV['MY_VAR'].presence || 'foobar'

The Demand gem which I wrote allows this to be extremely concise and DRY:
myvar = demand(ENV['MY_VAR'], 'foobar')
This will use ENV['MY_VAR'] only if it is present. That is, it will discard it just if it's nil, empty or a whitespace-only string, giving the default instead.
If a valid value for ENV['MY_VAR'] is falsy (such as false), or an invalid value is truthy (such as ""), then solutions like using || would not work.

I am new guy to Ruby, post the answer I found at 2021, maybe useful for someone.
check if env key exists:
include?(name) → true or false
has_key?(name) → true or false
member?(name) → true or false
key?(name) → true or false
get env with default value:
ENV.fetch(name, :default_val)
ref: https://docs.ruby-lang.org/en/master/ENV.html

myvar = ENV['MY_VAR'].is_set? ? ENV['MY_VAR'] : 'foobar'
This way you keep the .is_set? method.

Related

Variable defined despite condition should prevent it

Today I came across an interesting piece of code. It's more like a scientific question about the ruby parser.
We know everything in ruby is an object and every expression evaluates at least to nil.
But how is the following "assignment" parsed:
somevar
NameError: undefined local variable or method 'somevar' for main:Object
somevar = "test" if false
=> nil
somevar
=> nil
You see the variable is undefined until it's used in the assignment. But the assignment is not happening because of the condition. Or is it happening because the condition evaluates to nil? I tried something which would break in this case, but it just works:
a = {}
a[1/0]
ZeroDivisionError: divided by 0
a[1/0] = "test" if false
=> nil
So is this meant to work the way it is? Or does it make sense to test the variable (defined?(somevar)) before accessing, in case a future version of ruby will break this behaviour? As example by saving the assigned pointer to this variable.
My currently used ruby version is 3.0.2.
This is expected behavior in Ruby. Quote from the Ruby docs:
The local variable is created when the parser encounters the assignment, not when the assignment occurs:
a = 0 if false # does not assign to a
p local_variables # prints [:a]
p a # prints nil
If you do = "test" if false it evaluates to nil => no assignment needed. But by calling somevar = ... you told the interpreter to declare the name somevar. The nil aren't the same (if that makes sense).
The [] operator however doesn't declare a variable (only accesses) but since if false isn't true there is no assignment so the whole left side isnt evaluated.
Consider:
a = [1,2,3]
a[1] = "test" if false
a
=> [1,2,3]
a[1] is neither nil nor test.
Not sure what you expect or how future Ruby will break this?

Is there a simple way to evaluate a value to true/false without using an expression?

Is there a simple way in Ruby to get a true/false value from something without explicitly evaluating it to true or false
e.g. how would one more succinctly express
class User
def completed_initialization?
initialization_completed == 1 ? true : false
end
end
is there some way to do something along the lines of
initialization_completed.true?
There's obviously not much in it but since I'm in the zen garden of Ruby I might as well embrace it
EDIT (I've updated the example)
This question was extremely badly phrased as was very gently pointed out by #Sergio Tulentsev. The original example (below) does of course evaluate directly to a boolean. I'm still struggling to find an example of what I mean however Sergio's double-negative was in fact exactly what I was looking for.
Original example
class User
def top_responder
responses.count > 10 ? true : false
end
end
> operator already returns boolean value. So it can be just
def top_responder
responses.count > 10
end
To convert arbitrary values to booleans, I offer you this little double-negation trick.
t = 'foo'
!!t # => true
t = 1
!!t # => true
t = 0
!!t # => true
t = nil
!!t # => false
The first negation "casts" value to boolean and inverts it. That is, it will return true for nil / false and false for everything else. We need another negation to make it produce "normal" values.

Is !foo = expression legal in Ruby?

Note: I am not exactly sure what to name the question, so if someone has a better idea please edit it.
I will jump right into the question, since there isn't any fore-explaining required.
This code:
!foo = true
generates this warning
warning: found = in conditional, should be ==
I would understand if this was happening after an if or unless statement, but this couldn't be further away from them (exaggerating). I do realise I could use:
foo = true
!foo
I suppose, the warning isn't a big deal, but it is a bit irritating that Ruby is assuming I am doing something wrong—when I am not.
Questions:
Is this a bug?
Can the warning be disabled?
Thanks!
Is legal. Not a bug. The warning can be suppressed.
You can disable the warning with:
$VERBOSE = nil
It's interesting, $VERBOSE is a case where setting something to false does something different than setting it to nil.
By the way, the other answers, at least initially, tend to assume that Ruby parses the expression as
(!foo) = true
... but that's not the case. It is parsed as:
!(foo = true)
... and so it's doing exactly what the OP wanted. And there is no specification or ratified standard for Ruby, so if it works in MRI (the reference implementation) then it's legal.
As previous answers already suggested, that's not a valid thing of doing what you want to do.
!foo = true
evaluates as
!(foo = true)
That is, assign true to foo and get the negation of the result of that assignment, which boils down to
!true
or
false
If you want to store !true, it has to be
foo = !true
If you want to assign true to foo and the negation to another variable, it'd be
foo2 = !(foo = true)
and that will still cause a warning, because after all it is an assignment in a conditional.
I actually want to assign true to foo, and then get the opposite of foo on the stack
Doesn't really make much sense. You "get something on the stack" by assigning it to a variable, like foo2 in my example.
If the purpose here is to assign to an instance variable and return the negation from a method, then yes, you will have to first assign to the variable and then explicitly return the negation. This is not a bug in Ruby but actually a feature, and for the sake of clean code, you shouldn't be doing it in one line because it's basically indistinguishable from the common bug of using = when == was meant.
It's only a warning, and is evaluating as you expect. You can disable warnings temporarily by assigning $VERBOSE=nil.
save_verbose, $VERBOSE = $VERBOSE, nil
result = !foo = true
$VERBOSE = save_verbos
result
Other places on the net, suggest making a helper method ala
module Kernel
def silence_warnings
with_warnings(nil) { yield }
end
def with_warnings(flag)
old_verbose, $VERBOSE = $VERBOSE, flag
yield
ensure
$VERBOSE = old_verbose
end
end unless Kernel.respond_to? :silence_warnings
But, I just tried this in 1.9.2 and 1.8.7 and it was ineffective at suppressing the "warning: found = in conditional, should be =="
That's technically an invalid left hand assignment. You want
foo = !true
You can't assign a value to the opposite of the object. What is not foo? =)
This is a mistake in your code:
!var = anything
Is wrong. You're trying to assign to either TrueClass or FalseClass, which is (probably) what !var returns.
You want:
!var == true
Now you're doing the comparison (albeit an unnecessary one).

DRY up Ruby ternary

I often have a situation where I want to do some conditional logic and then return a part of the condition. How can I do this without repeating the part of the condition in the true or false expression?
For example:
ClassName.method.blank? ? false : ClassName.method
Is there any way to avoid repeating ClassName.method?
Here is a real-world example:
PROFESSIONAL_ROLES.key(self.professional_role).nil? ?
948460516 : PROFESSIONAL_ROLES.key(self.professional_role)
Assuming you're okay with false being treated the same way as nil, you use ||:
PROFESSIONAL_ROLES.key(self.professional_role) || 948460516
This will return 948460516 if key returns nil or false and the return value of the call to key otherwise.
Note that this will only return 948460516 if key returns nil or false, not if it returns an empty array or string. Since you used nil? in your second example, I assume that's okay. However you used blank? in the first example (and blank? returns true for empty arrays and strings), so I'm not sure.
If you just want to DRY, then you can use a temp variable:
x = ClassName.method
x.blank? ? false : x
x = PROFESSIONAL_ROLES.key(self.professional_role)
x.nil? ? 948460516 : x
If you don't want to use a temp variable, you can use a block:
Proc.new do |x| x.blank? ? false : x end.call(ClassName.method)
Proc.new do |x| x.nil? ? 948460516 : x end.call(PROFESSIONAL_ROLES.key(self.professional_role))
For the cases you describe (where you just want to use the original value when a default-check fails), it'd be straightforward to write a helper method:
def x_or_default(x, defval, checker = :nil?)
if x.send(checker) then defval else x end
end
x_or_default(ClassName.method, false, :blank?)
x_or_default(PROFESSIONAL_ROLES.key(self.professional_role), 94840516)
which is very similar to the || method described, but would also work with your blank? example.
I usually use temporary variables for this sort of thing.
I know this doesn't look too pretty, but it does make things a bit DRYer.
a = "ABC"
b = (temp = a.downcase).length < 3 ? "---" : temp
If you don't want to create temp variable for whatever reason, you could reuse something that already exists like $_.

What does !! mean in ruby?

Just wondering what !! is in Ruby.
Not not.
It's used to convert a value to a boolean:
!!nil #=> false
!!"abc" #=> true
!!false #=> false
It's usually not necessary to use though since the only false values to Ruby are nil and false, so it's usually best to let that convention stand.
Think of it as
!(!some_val)
One thing that is it used for legitimately is preventing a huge chunk of data from being returned. For example you probably don't want to return 3MB of image data in your has_image? method, or you may not want to return your entire user object in the logged_in? method. Using !! converts these objects to a simple true/false.
It returns true if the object on the right is not nil and not false, false if it is nil or false
def logged_in?
!!#current_user
end
! means negate boolean state, two !s is nothing special, other than a double negation.
!true == false
# => true
It is commonly used to force a method to return a boolean. It will detect any kind of truthiness, such as string, integers and what not, and turn it into a boolean.
!"wtf"
# => false
!!"wtf"
# => true
A more real use case:
def title
"I return a string."
end
def title_exists?
!!title
end
This is useful when you want to make sure that a boolean is returned. IMHO it's kind of pointless, though, seeing that both if 'some string' and if true is the exact same flow, but some people find it useful to explicitly return a boolean.
Note that this idiom exists in other programming languages as well. C didn't have an intrinsic bool type, so all booleans were typed as int instead, with canonical values of 0 or 1. Takes this example (parentheses added for clarity):
!(1234) == 0
!(0) == 1
!(!(1234)) == 1
The "not-not" syntax converts any non-zero integer to 1, the canonical boolean true value.
In general, though, I find it much better to put in a reasonable comparison than to use this uncommon idiom:
int x = 1234;
if (!!x); // wtf mate
if (x != 0); // obvious
It's useful if you need to do an exclusive or. Copying from Matt Van Horn's answer with slight modifications:
1 ^ true
TypeError: can't convert true into Integer
!!1 ^ !!true
=> false
I used it to ensure two variables were either both nil, or both not nil.
raise "Inconsistency" if !!a ^ !!b
It is "double-negative", but the practice is being discouraged. If you're using rubocop, you'll see it complain on such code with a Style/DoubleNegation violation.
The rationale states:
As this is both cryptic and usually redundant, it should be avoided
[then paraphrasing:] Change !!something to !something.nil?
Understanding how it works can be useful if you need to convert, say, an enumeration into a boolean. I have code that does exactly that, using the classy_enum gem:
class LinkStatus < ClassyEnum::Base
def !
return true
end
end
class LinkStatus::No < LinkStatus
end
class LinkStatus::Claimed < LinkStatus
def !
return false
end
end
class LinkStatus::Confirmed < LinkStatus
def !
return false
end
end
class LinkStatus::Denied < LinkStatus
end
Then in service code I have, for example:
raise Application::Error unless !!object.link_status # => raises exception for "No" and "Denied" states.
Effectively the bangbang operator has become what I might otherwise have written as a method called to_bool.
Other answers have discussed what !! does and whether it is good practice or not.
However, none of the answers give the "standard Ruby way" of casting a value into a boolean.
true & variable
TrueClass, the class of the Ruby value true, implements a method &, which is documented as follows:
Returns false if obj is nil or false, true otherwise.
Why use a dirty double-negation when the standard library has you covered?

Resources