Is assignment in a conditional clause good ruby style? - ruby

In order to write more concisely, rather than do this:
test_value = method_call_that_might_return_nil()
if test_value
do_something_with test_value
end
I've been assigning in the conditional:
if test_value = method_call_that_might_return_nil()
do_something_with test_value
end
Is this bad style? The still-more-concise syntax:
do_something_with test_value if test_value = method_call_that_might_return_nil()
is not allowed, as discussed in another SO question, and will remain that way in 1.9, according to Matz (http://redmine.ruby-lang.org/issues/show/1141).
Given the possible confusion of assignment and comparison, does this make it too hard to read the code?

It is GOOD style to use assignments in conditionals. If you do so, wrap the condition in parentheses.
# bad (+ a warning)
if v = array.grep(/foo/)
do_something(v)
# some code
end
# good (MRI would still complain, but RuboCop won't)
if (v = array.grep(/foo/))
do_something(v)
# some code
end
# good
v = array.grep(/foo/)
if v
do_something(v)
# some code
end
See the community style guide for more information

One somewhat widespread idiom is to use and, which would look something like this:
tmp = method_call_that_might_return_nil and do_something_with tmp
Another possibility would be to call #nil? explicitly, that way the intent becomes a little bit clearer; in particular it is really obvious that you actually meant to assign instead of compare:
unless (tmp = method_call_that_might_return_nil).nil?
do_something_with tmp
end

Concise code is not necessarily better code. Concision is useful when it improves the communication of intended code behavior from author to future maintainers. I think enough of us come from backgrounds in which we've had accidental assignments in if blocks (when we meant to have an equality comparison) that we prefer styles in which it's absolutely clear that assignment is meant, rather than comparison. The .nil? idiom already mentioned has that property, and I'd consider it cleaner than having the bare assignment inside the if condition. Really, though, I don't see the harm in having the extra line of code for the assignment.

The functional-programming way to do this is to use andand. It's a readable way of chaining method calls so that a nil in the middle stops the chain. So your example would be something like:
method_call_that_might_return_nil.andand.tap {|obj| do_something_with obj}
## or, in the common case: ##
method_call_that_might_return_nil.andand.do_something

Yeah, I would say it's bad style due to the possible confusion between assignment and comparison. It's only one more line to assign and then test, and it avoids having someone in the future think that was a bug and patch it to use == instead.

C programmers do this a lot. I don't see a problem with it in Ruby either so long as it's clear what's happening.

I think it's fine. Aversion to assignment in a condition comes from knowing that a missed key stroke when typing == turns a comparison into an unintended assignment. A stylistic prohibition on using assignment in a condition makes such accidents stand out like to the eye (and sometimes to the language, as in C, where many compilers can be made to emit a warning if they encounter an assignment in a condition). On the other hand, tests also make such accidents stand out. If your code is well covered by tests, you can consider discarding such prohibitions.

Due to the warning, performing the assignment in the if clause has a quite pungent smell. If you do have an else case to handle then the case ... in ... pattern matching can offer something:
case method_call_that_might_return_nil
in nil
# handle nil case
in test_value # pattern match to a new variable
# handle non-nil case with return value of method assigned to test_value
end
Or...
case method_call_that_might_return_nil
in test_value if test_value # pattern match to a new variable if not nil
# handle non-nil case with return value of method assigned to test_value
else
# handle nil case
end

Related

Ruby evaluates the default value in fetch even when key is found

h = {a: "foo"}
h.fetch(:a, h.fetch(:b))
yields key not found: :b
It seems strange that Ruby evaluates the default value even when the key is found? Is there a way around this?
Edit: Apparently this behavior falls under the paradigm of lazy vs eager evaluation. Nearly all imperative languages use eager evaluation, while many functional languages use lazy evaluation. However some languages, such as Python (which was before last week the only language I knew), have lazy evaluation capabilities for some operations.
It seems strange that Ruby evaluates the default value even when the key is found? Is there a way around this?
The overwhelming majority of mainstream programming languages is strict, i.e. arguments are fully evaluated before being passed. The only exception is Haskell, and calling it mainstream is a bit of a stretch.
So, no, it is not really "strange", it is how (almost) every language works, and it is also how every single other method in Ruby works. Every method in Ruby always fully evaluates all its arguments. That is, why, for example defined? and alias cannot be methods but must be builtin language constructs.
However, there is a way to delay evaluation, so to speak, using blocks: the content of a block is only evaluated each time it is called. Thankfully, Hash#fetch does take a block, so you can just use
h.fetch(:a) { h.fetch(:b) }
If you want the computation to only run if the key is not found, you can use the alternate form of fetch which accepts a block:
h.fetch(a) { h.fetch b }
I didn't actually know this was the case but I had a hunch and tried it and it worked. The reason I thought to try this was that something similar can be done in other methods such as gsub, i.e.
"123".gsub(/[0-9]/) { |i| i.to_i + 1 } == "234"
You could use the || operator instead, since it's lazy evaluated by design.
For example the following code where Nope is not defined does not throw an error.
{ a: "foo" }[:a] || Nope
However the fetch version will throw an error.
{ a: "foo" }.fetch(:a, Nope)
Personally I prefer how fetch is designed because it wont hide a bug in the default value.
However, in cases where I would rather not evaluate a default statement, then I would definitely reach for the || operator before doing something in a block or a lambda/proc.

Provide alias for Ruby's built-in keyword

For example, I want to make Object#rescue another name so I can use in my code like:
def dangerous
something_dangerous!
dont_worry # instead of rescue here
false
end
I tried
class ::Object
alias :dont_worry :rescue
end
But cannot find the rescue method on Object:
`<class:Object>': undefined method `rescue' for class `Object' (NameError)
Another example is I would like to have when in the language to replace:
if cond
# eval when cond is truthy
end
to
when cond
# eval when cond is truthy
end
Is it possible to give a Ruby keyword alias done in Ruby?
Or I need to hack on Ruby C source code?
Thanks!
This is not possible without some deep changes to the Ruby language itself. The things you describe are not methods but keywords of the language, i.e. the actual core of what is Ruby. As such, these things are not user-changeable at all.
If you still want to change the names of the keywords, you would at least have to adapt the language parser. If you don't change semantics at all, this might do it as is. But if you want to change what these keywords represent, things get messy really quick.
Also note that Ruby in itself is sometimes quite ambiguous (e.g. with regards to parenthesis, dots, spacing) and goes to great length to resolve this in a mostly consistent way. If you change keywords, you would have to ensure that things won't get any more ambiguous. This could e.g. happen with your change of if to when. when is used as a keywords is case statements already and would thus could be a source of ambiguity when used as an if.

is it best practice to define vars first before using them inside a begin block?

foo = ''
begin
foo = 'hi there'
rescue
end
puts foo
if I don't delcare foo = '' at the top before the begin it still works. But I see a lot of people do this. And it feels better. But is it best practice?
This is part paranoia, and part clarity. In this trivial example there's unlikely to be an issue, but what if you had this?
begin
foo = complicated_method_call(with: lots_of_arguments, and: another_call(with: args))
rescue
end
A whole bunch of stuff could go wrong there, and if that's the case you end up with foo being nil.
Now, using a blind rescue is generally bad form, you ideally want to scope down to just the ones your code might trigger.
Remember Ruby variables are defined at the method level, any instance of them in the method makes them defined, but they will have a default of nil which can be undesirable.
As you already know, for Ruby the variable exists whenever you assign a value/object to it, making it a weakly/loosely-typed (as opposed to "strongly typed") language. Why? The focus of the language's designer was simplicity and easy of use -- see the statement in the manual :). Remember also that there isn't a need to write 'return' inside methods to return values nor write parenthesis when calling functions if there isn't confusion. Why? Simplicity, ease of use. Hard to tell if these things are better or not as a general answer. Do we have to rely always upon the compiler checks? Are we pro? Really? But generally speaking, we can hardly find ruby programmers declaring variables always unless instance/global ones, and at the end we'll getting ourselves rushing in the mainstream. Yay! General answer to determine the type of a variable: https://en.wikipedia.org/wiki/Duck_test Have fun!

What's the purpose of using the suffix "if" statement in Ruby?

I know Ruby supports a suffix if like:
number = -42 if opposite
but what's the purpose of this? Why would it be used in place of the prefix if statement?
The suffix-style if and unless can also be good for "guard clauses", in the form of:
return if ...
return unless ...
Here's an example:
# suffix-style
def save
return false if invalid?
# go for it
true
end
Versus:
# indented style
def save
if valid?
# go for it
true
else
false
end
end
In the second example, the entire implementation of the method has to be shifted over by one indent due to the valid? check, and we need an extra else clause. With the suffix style, the invalid? check is considered an edge case that we handle and then bail out, and the rest of the method doesn't need an indent or an else clause.
This is sometimes called a "guard clause" and is recommended by the Ruby Style Guide.
It can make the code easier to read in some cases. I find this to be true especially in the case of unless, where you have some action you usually want to perform:
number = -42 unless some_unusual_circumstance_holds
Once you have it for unless, for symmetry it makes sense to support it for if as well.
number = -42 if opposite
is the same as
if opposite
number = -42
end
Some people prefer the one-liner for readability reasons. Imagine a line like:
process_payment if order_fulfilled?
Doesn't that read nice?
Postfix style does not have the else section. It is useful when you only want to do something with one of the two cases divided by the condition and don't want to mess with the other case.
It's the same as prefix but shorter. The only reason is to save vertical space in the text editor.

better way to do assignment and check result

I have to use String.scan function, which returns empty array if there is no match.
I wanted to assign a variable with the scan function and check it there is a match, but unfortunately I cannot do that because it won't return nil or false on no match.
I wanted to do this (1 line):
if ip = str.scan(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)
...
#use ip
end
but because it won't return nil on no match I must do:
ip_match = str.scan(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)
unless ip_match.empty?
#use ip
end
Is there some more elegant way to write this - to be able to do assignment and empty check at the same time or some other way to beautify the code?
Thanks
Since scan returns an array, and even if you are sure there would be only one result, you could do this.
str.scan(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/).each do |ip|
#use ip
end
There's a difference between elegant and cryptic or "concise".
In Perl you'll often see people write something equivalent to:
if (!(ip = str.scan(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)).empty?)
It's a bit more concise, terse, tight, whatever you want to call it. It also leads to maintenance issues because of the = (equate) vs. what should normally be an equality test. If the code is passed to someone who doesn't understand the logic, they might mistakenly "correct" that, and then break the code.
In Ruby it's idiomatic to not use equate in a conditional test, because of the maintenance issue, and instead use the assignment followed by a test. It's clearer code.
Personally, I prefer to not use unless in that sort of situation. It's an ongoing discussion whether unless helps generate more understandable code; I prefer if (!ip_match.empty?) because it reads more like we'd normally talk -- I seldom start a statement with unless in conversation. Your mileage might vary.
I would preferably do something like this using String helper match
ip_validator = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
# match return nil if no match
if str.match ip_validator
# blah blah blah.....
end
help me keep code dry and clean.
May be this is not the most elegant , looking for others if any :)
Your ip_validator regex seems to be week check this out Rails 3: Validate IP String

Resources