Elegant way of changing a variable in Ruby if it equals a specific value

Viewed 109

I am looking for a more elegant way to do this:

my_var = nil if my_var == 2

Currently I have to repeat my_var twice which doesn't read or look very nice.

This becomes even more ugly if I my_var is a key from a hash:

my_hash[:my_key] = nil if my_hash[:my_key] == 12

If I wanted to change it only if it was already nil then I could do this:

my_var ||= 2

Which is much cleaner.

Is there any nicer way of changing a variables value if it is equal to a certain value?

1 Answers

It sounds like you want to use sentinel values to represent nil values.

Here's one way, which may or may not exactly fit your situation. First, define a function that generates your nilifier, based on your chosen sentinel value:

def make_nilifier sentinel
  -> (var) { var == sentinel ? nil : var }
end

In your first example, the sentinel values is 2:

nilifier = make_nilifier 2

Then, you can assign values to my_var via calls to the nilifier:

> my_var = nilifier.call 1
> my_var
=> 1

> my_var = nilifier.call 2
> my_var
=> nil

In your case, you are checking values that are already set - this provides a way to check the value on assignment. Again, it may or may not exactly fit, but may give some ideas toward something useful.

Related