Is Assignment in a Conditional Clause Good Ruby Style

Is assignment in a conditional clause good ruby style?

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

Why does conditional statement and assigning value in ruby fails if the if statement is at end of clause?

It fails because of the way the parser works.

From the parser's point of view the variable tmp2 exists from the point in the code at which it is first assigned until the point where it goes out of scope. For this it does not matter, when (or if) the assignment is actually executed, just when the parser sees the assignment (i.e. it depends on the assignments position in the code).

Edit: To expand on that bit:

The decision whether a name is a local variable or a method call is made by the parser. The parser makes that decision solely based on whether or not it has already seen an assignment to that variable. So when the parser sees tmp2 before seeing tmp2 = ..., it decides that here tmp2 refers to a method. When that part of the code is actually executed, it tries to call the method tmp2 which does not exist so you get the error.

Ruby variable assignment in a conditional if modifier

Read it carefully :

Another commonly confusing case is when using a modifier if:

p a if a = 0.zero?

Rather than printing true you receive a NameError, “undefined local variable or method 'a'”. Since Ruby parses the bare a left of the if first and has not yet seen an assignment to a it assumes you wish to call a method. Ruby then sees the assignment to a and will assume you are referencing a local method.

The confusion comes from the out-of-order execution of the expression. First the local variable is assigned-to then you attempt to call a nonexistent method.

As you said - None return foo if (foo = bar.some_method) and return foo if (true && (foo = bar.some_method)) will work, I bet you, it wouldn't work, if you didn't define foo before this line.

Style/ConditionalAssignment: Use the return of the conditional for variable assignment and comparison

Instead of

if inactive_list.include? <<id of data>>
data[:active] = false
else
data[:active] = true
end

you can just write

data[:active] = !inactive_list.include? <<id of data>>

Or when you are using Rails then you can use exclude? instead of the negation of include?:

data[:active] = inactive_list.exclude? <<id of data>>

Full example:

data = {
name: "Test",
full_name: "Test data",
active: inactive_list.exclude?(<<id of data>>)
}

Ruby conditional assignment

So you ask for the upper limit:

UPPER_LIMIT = 25
b = 100
a = [b, UPPER_LIMIT].min

a will always smaller or equal to 25.

Recommended indentation style for Ruby `if` blocks that assign a value to a variable?

It's a subjective question, so we can only give (hopefully reasoned) opinions. I always use option A. My rationale:

  1. The block of code is opened and closed at the same indentation-level, that creates a "visual cohesion".

  2. If the variable name changes its size, you don't need to edit anything (some text editors handle this automatically, though).

  3. You create a "hole" in the source code. The larger the variable name, the bigger the hole. IMO this is visually annoying. Also, you have less space available till reaching some reasonable 80/100-char limit.

I use this style when writing multi-line hashes/arrays/... (note the comma also in the last element so we can re-order them easily and in diff-friendly way):

hash = {
:a => 1,
:b => 2,
}

array = [
:a,
:b,
]

Conditional assignment in Ruby

It basically leans on Ruby's falsy objects: nil and false.

Everything except for nil and false is said to be truthy in Ruby.

So in the example it prints the value of @two if it's truthy (2), otherwise (nil) it prints the error message.

I do not think this "concept" has a name.

if statement after variable assignment - how common?

The fact that if and case return values makes for some very tight, tidy, and yet still understandable code. It's a common pattern in Ruby when you're dealing with assignment through branching.

The way I tend to approach formatting these is to apply a level of indentation to make the assignment clear, but not overly "push" the code in too far:

value =
if a == 0
"foo"
elsif a > 42
"bar"
else
"fizz"
end

Or if you want a case:

value =
case
when a == 0
"foo"
when a > 42
"bar"
else
"fizz"
end

In many cases you'll see a method that has an if as the body to determine the result:

def value(a)
if a == 0
"foo"
elsif a > 42
"bar"
else
"fizz"
end
end

Then there's no quirky indentation necessary.

Refactoring conditional variable assignment

Just put the assignment outside the if.

x = if some condition
some value
elsif another condition
a different value

Or you could use a Hash.

x = dict[some condition]


Related Topics



Leave a reply



Submit