Ruby Tricks, Idiomatic Ruby, Refactorings and Best Practices

Conditional assignment.

Ruby is heavily influenced by lisp. One piece of obvious inspiration in its design is that conditional operators return values. This makes assignment based on conditions quite clean and simple to read.

There are quite a number of conditional operators you can use. Optimize for readability, maintainability, and concision.

If you're just assigning based on a boolean, the ternary operator works best (this is not specific to ruby/lisp but still good and in the spirit of the following examples!).

If you need to perform more complex logic based on a conditional or allow for > 2 outcomes, if / elsif / else statements work well.

If you're assigning based on the value of a single variable, use case / when A good barometer is to think if you could represent the assignment in a hash. For example, in the following example you could look up the value of opinion in a hash that looks like {"ANGRY" => comfort, "MEH" => ignore ...}

Conditional Logic

Ruby course, introduction.

This lesson is all about controlling the flow of your code. When you have some code that you only want to execute under specific conditions, you will need a way for the computer to check whether those conditions have been met. Conditional logic can be found everywhere in everyday life. Ever had to tidy your room before being allowed to play video games? That’s your mother setting up a nice conditional statement that might look like this in a computer program…

There must be a motherboard joke in there somewhere. Answers on a postcard!

Any conditional statement will always have an expression that evaluates to true or false . Based on this answer, the computer will decide whether or not to execute the code that follows. If it’s true, then the code will be processed; if it’s false, the code will be skipped, and you can provide some other code that will be run instead. There can even be several conditional statements on one line, but keep in mind that too many can make code look cluttered.

You’ll write a lot of conditional statements on your road to programmer stardom. Although they are fundamentally simple, they are a big source of bugs in your code when something isn’t working as expected. Make sure you understand the logic behind the expression being evaluated so you can step through it if you need to.

Lesson overview

This section contains a general overview of topics that you will learn in this lesson.

  • Describe and list falsy values.
  • Explain how to use if , elsif , and else .
  • Explain the difference between if and unless .
  • Describe what || , && , and ! do.
  • Explain what short circuit evaluation is.
  • Describe what the ternary operator is and how to use it.
  • Explain what a case statement is and how it works.

Truthy and falsy in Ruby

You already know that conditional statements check expressions for a true or false value, so it follows that you need to understand what Ruby considers to be true or false. In typical Ruby fashion, it’s very simple. The only false values in Ruby are the values nil and false themselves. That’s it! Everything else is considered true. Even the string "false" is true in conditional expressions! If you have experience with other programming languages, you might be familiar with the number 0 or an empty string (“”) being equivalent to false. This isn’t the case with Ruby, so be careful when writing those expressions, or you’ll have more bugs than a decomposing body.

Basic conditional statement

The simplest way to control the flow of your code using conditionals is with the if statement.

The general syntax of an if statement is shown here:

If there is only one line of code to be evaluated inside the block, then you can rewrite the code to be more succinct and take up only one line:

You don’t even need the end statement. Nice and concise!

The statement to be evaluated can be anything that returns true or false. It could be a mathematical expression, a variable value, or a call to a method. Only if the expression evaluates to true does the code inside the block run.

Adding else and elsif

We often want to check a condition and run some code if it’s true but then run some other code if it’s false. This is done with an if...else statement.

Oh yeah! Protected on land and sea.

But what about if we’re attacked by air? We need yet another conditional check. Enter the if...elsif...else statement!

Ain’t nobody pillaging our land!

You can have as many elsif expressions as you want. The else clause is optional, but you usually want to provide some default value in case none of the previous expressions evaluate to true .

Boolean logic

To determine whether an expression evaluates to true or false , you’ll need a comparison operator. There are several provided by Ruby:

== (equals) returns true if the values compared are equal.

!= (not equal) returns true if the values compared are not equal.

> (greater than) returns true if the value on the left of the operator is larger than the value on the right.

< (less than) returns true if the value on the left of the operator is smaller than the value on the right.

>= (greater than or equal to) returns true if the value on the left of the operator is larger than or equal to the value on the right.

<= (less than or equal to) returns true if the value on the left of the operator is smaller than or equal to the value on the right.

#eql? checks both the value type and the actual value it holds.

#equal? checks whether both values are the exact same object in memory. This can be slightly confusing because of the way computers store some values for efficiency. Two variables pointing to the same number will usually return true .

This expression is true because of the way computers store integers in memory. Although two different variables are holding the number 5, they point to the same object in memory. However, consider the next code example:

This happens because computers can’t store strings in the same efficient way they store numbers. Although the values of the variables are the same, the computer has created two separate string objects in memory.

In addition to the above operators, Ruby has a special operator that is affectionately referred to as the spaceship operator . Unlike the other comparison operators, which all return true or false , the spaceship operator returns one of three numerical values.

<=> (spaceship operator) returns the following:

  • -1 if the value on the left is less than the value on the right;
  • 0 if the value on the left is equal to the value on the right; and
  • 1 if the value on the left is greater than the value on the right.

The spaceship operator is most commonly used in sorting functions, which we’ll cover more later.

All of the above operators also work on data types other than numbers, such as strings. Why not play around with this in a REPL?

Logical operators

Sometimes you’ll want to write an expression that contains more than one condition. In Ruby, this is accomplished with logical operators, which are && (and), || (or) and ! (not).

There are some differences between the word versions and their symbolic equivalents, particularly in the way they evaluate code. We recommend you read this article that explains the differences.

The && operator returns true if both the left and right expressions return true .

One thing to keep in mind with the && and || operators is the order of logic. The expressions are always evaluated from left to right.

Using the && operator, both expressions must return true . If the first expression encountered returns false , then the second expression is never checked. To the Ruby interpreter, it’s pointless to evaluate the second half as the overall expression can never return true .

With the || operator, if the first expression evaluates to true , then the second expression is never checked because the complete expression is already true , and the code in the block is run.

This is known as short circuit evaluation .

The ! operator reverses the logic of the expression. Therefore, if the expression itself returns false , using the ! operator makes the expression true , and the code inside the block will be executed.

Case statements

Case statements are a neat way of writing several conditional expressions that would normally result in a messy if...elsif statement. You can even assign the return value from a case statement to a variable for use later.

Case statements process each condition in turn, and if the condition returns false , it will move onto the next one until a match is found. An else clause can be provided to serve as a default if no match is found.

As soon as a match is found, the value of that match is returned, and the case statement stops execution. Can you tell what the value of the did_i_pass variable is going to be after the case statement?

If you need to do some more complex code manipulation, you can remove the then keyword and instead place the code to be executed on the next line.

Unless statements

An unless statement works in the opposite way as an if statement: it only processes the code in the block if the expression evaluates to false . There isn’t much more to it.

Just like with if statements, you can write an unless statement on one line, and you can also add an else clause.

You should use an unless statement when you want to not do something if a condition is true , because it can make your code more readable than using if !true .

Ternary operator

The ternary operator is a one-line if...else statement that can make your code much more concise.

Its syntax is conditional statement ? <execute if true> : <execute if false> . You can assign the return value of the expression to a variable.

Here, because the expression evaluated to false , the code after the : was assigned to the variable response .

Writing this as an if...else statement would be much more verbose:

However, if your conditional statements are complicated, then using an if...else statement can help to make your code more readable. Remember, above all else, your code needs to be readable and understandable by other people , especially in the development stage. You can always optimize your code for efficiency once it’s finished and you’re moving to a production environment where speed matters.

  • For more depth, read the Flow Control chapter from LaunchSchool’s Introduction to Programming With Ruby .
  • For an overview of flow control, read through this Ruby Explained: Conditionals and Flow Control article.

Knowledge check

This section contains questions for you to check your understanding of this lesson. If you’re having trouble answering the questions below on your own, review the material above to find the answer.

  • What is a Boolean?
  • What are “truthy” values?
  • Are the following considered true or false: nil , 0 , "0" , "" , 1 , [] , {} and -1 ?
  • When do you use elsif ?
  • When do you use unless ?
  • What do || and && and ! do?
  • What is short circuit evaluation?
  • What is returned by puts("woah") || true ?
  • What is the ternary operator?
  • When should you use a case statement?

Additional resources

This section contains helpful links to related content. It isn’t required, so consider it supplemental.

  • For more on the spaceship operator, see this Stack Overflow post .
  • For more depth on flow control, read Zetcode’s Flow Control section .
  • If you want some in-depth practice with these concepts, go through Learn Ruby the Hard Way from Exercise 27 through Exercise 31.

Support us!

The odin project is funded by the community. join us in empowering learners around the globe by supporting the odin project.

Ruby Gotcha: single line conditionals

Jul 31, 2012

I’ve touched on this gotcha briefly in the past when discussing the Wat video , but I thought a few examples of when single-line conditionals can bite you would be fun.

In Ruby, we can write a conditional containing a single expression that normally takes up three lines:

on a single line to save space:

And that is all well and good - these two are pretty much the same. But they’re not identical in practice. There are a few weird things about to come up.

Our first example will be using defined? to conditionally print a variable

So that works just as we’d expect. The conditional never runs because defined?(var1) returns nil . After the conditional, access the undefined var1 gives us a NameError because (appropriately) its not defined. Let’s modify that a little bit and put an assignment inside of the conditional.

So that might look a bit odd. We never ran the conditional, so var2 never gets set - that makes sense. But after the block, var2 doesn’t throw a NameError when accessed anymore. This is because the Ruby parser makes room and defines var2 when it sees it on the lefthand side of an expression (even though its inside of a conditional that doesn’t run).

Let’s write the same on one line though:

Even more interesting - an undefined variable written this way will become defined and assigned when run. The first thing that happens is that the parser comes along and defines var3 which it sees on the lefthand side of a conditional. Then defined? runs, which this time evaluates to "local-variable" , causing the conditional to pass, and 5 to be assigned to var3 . In cases like this, the single-line conditional will produce an entirely different result than block conditionals.

CodingDrills logo

Conditional Statements in Ruby

Conditional statements are an essential part of any programming language, including Ruby. They give us the ability to make decisions and alter the flow of our code based on certain conditions. In this tutorial, we will delve into the basics of conditional statements in Ruby, exploring various types and their usage.

If Statements

The most basic form of a conditional statement is the if statement. It allows us to execute a block of code only if a certain condition is met.

Here is a simple example:

In this example, we first declare a variable age with a value of 25. The if statement checks whether age is greater than 18. If the condition evaluates to true, the code inside the if block is executed, and the message "You are an adult!" is printed.

We can also add an else block after the if block to handle cases when the condition is not met. Taking the previous example further:

In this case, since age is 16, the condition age > 18 is false, and thus the code in the else block is executed, printing "You are not yet an adult."

ElseIf Statements

Ruby provides the elsif statement as a way to add additional conditions to our if statements. This allows us to handle multiple possible outcomes in a more organized manner.

Consider the following example:

In this example, we have multiple conditions. If age is less than 18, the first if block is executed. If not, the program checks the next condition using the elsif keyword. If age is between 18 and 65, the second elsif block is executed. Finally, if none of the previous conditions are met, the code inside the else block is executed.

Case Statements

Another way to handle conditional statements in Ruby is by using case statements. These statements can be helpful when dealing with multiple possible values for a variable.

Here is an example:

In this case statement, we check the value of the variable day . Depending on its value, different code blocks are executed. In this example, since day is "Monday," the code inside the first when block is executed, printing "It's the beginning of the week."

Case statements also support ranges and multiple conditions for each when block. They are a flexible tool for handling complex conditional logic.

Conditional statements are a crucial aspect of programming in any language, and Ruby is no exception. They provide us with the ability to control the flow of our code based on specific conditions. In this tutorial, we explored the basics of conditional statements in Ruby, including if statements, elsif statements for multiple conditions, and case statements for handling various possible values.

With the knowledge gained from this tutorial, you are now equipped to use conditional statements effectively in your Ruby programs. Happy coding!

Remember to save this Markdown file and convert it to HTML using your preferred Markdown converter to properly format and present the content on your blog.

CodingDrills logo

Hi, I'm Ada, your personal AI tutor. I can help you with any coding tutorial. Go ahead and ask me anything.

I have a question about this topic

Give more examples

Ruby Assignments in Conditional Expressions

For around two and a half years, I had been working in a Python 2.x environment at my old job . Since switching companies, Ruby and Rails has replaced Python and Flask. At first glance, the languages don’t seem super different, but there are definitely common Ruby idioms that I needed to learn.

While adding a new feature, I came across code that looked like this:

Intuitively, I guessed this meant “if some_func() returns something, do_something with it.” What took a second was understanding that you could do an assignment conditional expressions.

Coming from Python

In Python 2.x land (and any Python 3 before 3.8), assigning a variable in a conditional expression would return a syntax error:

Most likely, the assignment in a conditional expression is a typo where the programmer meant to do a comparison == instead.

This kind of typo is a big enough issue that there is a programming style called Yoda Conditionals , where the constant portion of a comparison is put on the left side of the operator. This would cause a syntax error if = were used instead of == , like this:

Back to Ruby

Now that I’ve come across this kind of assignment in Ruby for the first time, I searched whether assignments in conditional expressions were good style. Sure enough, the Ruby Style Guide has a section called “Safe Assignment in Condition” . The section and examples are short and straightforward. You should take a look if this Ruby idiom is new to you!

What is interesting about this idiom is that the assignment should be wrapped in parentheses. Take a look at the examples from the Ruby Style Guide:

Why is the first example bad? Well, the Style Guide also says that you shouldn’t put parentheses around conditional expressions . Parentheses around assignments in conditional expressions are specifically called out as an exception to this rule.

My guess is that by enforcing two different conventions, one for pure conditionals and one for assignments in conditionals, the onus is now on the programmer to decide what they want to do. This should prevent typos where an assignment = is used when a comparison == was intended, or vice versa.

The Python Equivalent

As called out above, assignments in conditional expressions are possible in Python 3.8 via PEP 572 . Instead of using an = for these kinds of assignments, the PEP introduced a new operator := . As parentheses are more common in Python expressions, introducing a new operator := (informally known as “the walrus operator”!!) was probably Python’s solution to the typo issue.

Ruby One-Liners Guide

One-liner introduction, why use ruby for one-liners, installation and documentation, command line options, executing ruby code.

See ruby-doc: Pre-Defined Global Variables for documentation on $_ , $& , etc.
The example_files directory has all the files used in the examples (like table.txt in the above illustration).

Substitution

This book assumes that you are already familiar with regular expressions. If not, you can check out my free ebook Understanding Ruby Regexp .

Field processing

Begin and end.

As an example, see my repo ch: command help for a practical shell script, where commands are constructed dynamically.

Executing external commands

See also stackoverflow: difference between exec, system and %x() or backticks .
All the exercises are also collated together in one place at Exercises.md . For solutions, see Exercise_solutions.md .
The exercises directory has all the files used in this section.

Ruby Style Guide

Table of contents, guiding principles, a note about consistency, translations, source encoding, tabs or spaces, indentation, maximum line length, no trailing whitespace, line endings, should i terminate files with a newline, should i terminate expressions with ; , one expression per line, operator method call, spaces and operators, safe navigation, spaces and braces, no space after bang, no space inside range literals, indent when to case, indent conditional assignment, empty lines between methods, two or more empty lines, empty lines around attribute accessor, empty lines around access modifier, empty lines around bodies, trailing comma in method arguments, spaces around equals, line continuation in expressions, multi-line method chains, method arguments alignment, implicit options hash, dsl method calls, space in method calls, space in brackets access, multi-line arrays alignment, english for identifiers, snake case for symbols, methods and variables, identifiers with a numeric suffix, capitalcase for classes and modules, snake case for files, snake case for directories, one class per file, screaming snake case for constants, predicate methods suffix, predicate methods prefix, dangerous method suffix, relationship between safe and dangerous methods, unused variables prefix, other parameter, then in multi-line expression, condition placement, ternary operator vs if, nested ternary operators, semicolon in if, case vs if-else, returning result from if / case, one-line cases, semicolon in when, semicolon in in, double negation, multi-line ternary operator, if as a modifier, multi-line if modifiers, nested modifiers, if vs unless, using else with unless, parentheses around condition, multi-line while do, while as a modifier, while vs until, infinite loop, loop with break, explicit return, explicit self, shadowing methods, safe assignment in condition, begin blocks, nested conditionals, raise vs fail, raising explicit runtimeerror, exception class messages, return from ensure, implicit begin, contingency methods, suppressing exceptions, using rescue as a modifier, using exceptions for flow of control, blind rescues, exception rescuing ordering, reading from a file, writing to a file, release external resources, auto-release external resources, atomic file operations, standard exceptions, parallel assignment, values swapping, dealing with trailing underscore variables in destructuring assignment, self-assignment, conditional variable initialization shorthand, existence check shorthand, identity comparison, explicit use of the case equality operator, is_a vs kind_of, is_a vs instance_of, instance_of vs class comparison, proc application shorthand, single-line blocks delimiters, single-line do …​ end block, explicit block argument, trailing comma in block parameters, nested method definitions, multi-line lambda definition, stabby lambda definition with parameters, stabby lambda definition without parameters, proc vs proc.new, short methods, top-level methods, no single-line methods, endless methods, double colons, colon method definition, method definition parentheses, method call parentheses, too many params, optional arguments, keyword arguments order, boolean keyword arguments, keyword arguments vs optional arguments, keyword arguments vs option hashes, arguments forwarding, block forwarding, private global methods, consistent classes, mixin grouping, single-line classes, file classes, namespace definition, modules vs classes, module_function, solid design, define to_s, attr family, accessor/mutator method names, don’t extend struct.new, don’t extend data.define, duck typing, no class vars, leverage access modifiers (e.g. private and protected ), access modifiers indentation, defining class methods, alias method lexically, alias_method, class and self, defining constants within a block, factory methods, disjunctive assignment in constructor, no comments, rationale comments, english comments, english syntax, no superfluous comments, comment upkeep, refactor, don’t comment, annotations placement, annotations keyword format, multi-line annotations indentation, inline annotations, document annotations, magic comments first, below shebang, one magic comment per line, separate magic comments from code, literal array and hash, no trailing array commas, no gappy arrays, first and last, set vs array, symbols as keys, no mutable keys, hash literals, hash literal values, hash literal as last array item, no mixed hash syntaxes, avoid hash[] constructor, hash#fetch defaults, use hash blocks, hash#values_at and hash#fetch_values, hash#transform_keys and hash#transform_values, ordered hashes, no modifying collections, accessing elements directly, provide alternate accessor to collections, map / find / select / reduce / include / size, count vs size, reverse_each, object#yield_self vs object#then, slicing with ranges, underscores in numerics, numeric literal prefixes, integer type checking, random numbers, float division, float comparison, exponential notation, string interpolation, consistent string literals, no character literals, curlies interpolate, string concatenation, don’t abuse gsub, string#chars, named format tokens, long strings, squiggly heredocs, heredoc delimiters, heredoc method calls, heredoc argument closing parentheses, no datetime, plain text search, using regular expressions as string indexes, prefer non-capturing groups, do not mix named and numbered captures, refer named regexp captures by name, avoid perl-style last regular expression group matchers, avoid numbered groups, limit escapes, caret and dollar regexp, multi-line regular expressions, comment complex regular expressions, use gsub with a block or a hash for complex replacements, %q shorthand, percent literal braces, no needless metaprogramming, no monkey patching, block class_eval, eval comment docs, no method_missing, prefer public_send, prefer __send__, rd (block) comments, no ruby_version in the gemspec, no flip-flops, no non- nil checks, global input/output streams, array coercion, ranges or between, predicate methods, no cryptic perlisms, use require_relative whenever possible, always warn, no optional hash params, instance vars, optionparser, no param mutations, three is the number thou shalt count, functional code, no explicit .rb to require, sources of inspiration, how to contribute, spread the word, introduction.

Role models are important.

This Ruby style guide recommends best practices so that real-world Ruby programmers can write code that can be maintained by other real-world Ruby programmers. A style guide that reflects real-world usage gets used, while a style guide that holds to an ideal that has been rejected by the people it is supposed to help risks not getting used at all - no matter how good it is.

The guide is separated into several sections of related guidelines. We’ve tried to add the rationale behind the guidelines (if it’s omitted we’ve assumed it’s pretty obvious).

We didn’t come up with all the guidelines out of nowhere - they are mostly based on the professional experience of the editors, feedback and suggestions from members of the Ruby community and various highly regarded Ruby programming resources, such as "Programming Ruby" and "The Ruby Programming Language" .

This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in Ruby itself.

Programs must be written for people to read, and only incidentally for machines to execute.

It’s common knowledge that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Ruby code. They are also meant to reflect real-world usage of Ruby instead of a random ideal. When we had to choose between a very established practice and a subjectively better alternative we’ve opted to recommend the established practice. [ 1 ]

There are some areas in which there is no clear consensus in the Ruby community regarding a particular style (like string literal quoting, spacing inside hash literals, dot position in multi-line method chaining, etc.). In such scenarios all popular styles are acknowledged and it’s up to you to pick one and apply it consistently.

Ruby had existed for over 15 years by the time the guide was created, and the language’s flexibility and lack of common standards have contributed to the creation of numerous styles for just about everything. Rallying people around the cause of community standards took a lot of time and energy, and we still have a lot of ground to cover.

Ruby is famously optimized for programmer happiness. We’d like to believe that this guide is going to help you optimize for maximum programmer happiness.

A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines.

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one class or method is the most important.

However, know when to be inconsistent — sometimes style guide recommendations just aren’t applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don’t hesitate to ask!

In particular: do not break backwards compatibility just to comply with this guide!

Some other good reasons to ignore a particular guideline:

When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this style guide.

To be consistent with surrounding code that also breaks it (maybe for historic reasons) — although this is also an opportunity to clean up someone else’s mess (in true XP style).

Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.

When the code needs to remain compatible with older versions of Ruby that don’t support the feature recommended by the style guide.

Translations of the guide are available in the following languages:

Chinese Simplified

Chinese Traditional

Egyptian Arabic

Portuguese (pt-BR)

Source Code Layout

Nearly everybody is convinced that every style but their own is ugly and unreadable. Leave out the "but their own" and they’re probably right…​

Use UTF-8 as the source file encoding.

Use only spaces for indentation. No hard tabs.

Use two spaces per indentation level (aka soft tabs).

Limit lines to 80 characters.

A lot of people these days feel that a maximum line length of 80 characters is just a remnant of the past and makes little sense today. After all - modern displays can easily fit 200+ characters on a single line. Still, there are some important benefits to be gained from sticking to shorter lines of code.

First, and foremost - numerous studies have shown that humans read much faster vertically and very long lines of text impede the reading process. As noted earlier, one of the guiding principles of this style guide is to optimize the code we write for human consumption.

Additionally, limiting the required editor window width makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns.

The default wrapping in most tools disrupts the visual structure of the code, making it more difficult to understand. The limits are chosen to avoid wrapping in editors with the window width set to 80, even if the tool places a marker glyph in the final column when wrapping lines. Some web based tools may not offer dynamic line wrapping at all.

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 100 characters, or all the way up to 120 characters. Please, restrain the urge to go beyond 120 characters.

Avoid trailing whitespace.

Use Unix-style line endings. [ 2 ]

End each file with a newline.

Don’t use ; to terminate statements and expressions.

Use one expression per line.

Avoid dot where not required for operator method calls.

Use spaces around operators, after commas, colons and semicolons. Whitespace might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code.

There are a few exceptions:

Exponent operator:

Slash in rational literals:

Safe navigation operator:

Avoid chaining of &. . Replace with . and an explicit check. E.g. if users are guaranteed to have an address and addresses are guaranteed to have a zip code:

If such a change introduces excessive conditional logic, consider other approaches, such as delegation:

No spaces after ( , [ or before ] , ) . Use spaces around { and before } .

{ and } deserve a bit of clarification, since they are used for block and hash literals, as well as string interpolation.

For hash literals two styles are considered acceptable. The first variant is slightly more readable (and arguably more popular in the Ruby community in general). The second variant has the advantage of adding visual difference between block and hash literals. Whichever one you pick - apply it consistently.

With interpolated expressions, there should be no padded-spacing inside the braces.

No space after ! .

No space inside range literals.

Indent when as deep as case .

This is the style established in both "The Ruby Programming Language" and "Programming Ruby". Historically it is derived from the fact that case and switch statements are not blocks, hence should not be indented, and the when and else keywords are labels (compiled in the C language, they are literally labels for JMP calls).

When assigning the result of a conditional expression to a variable, preserve the usual alignment of its branches.

Use empty lines between method definitions and also to break up methods into logical paragraphs internally.

Don’t use several empty lines in a row.

Use empty lines around attribute accessor.

Use empty lines around access modifier.

Don’t use empty lines around method, class, module, block bodies.

Avoid comma after the last parameter in a method call, especially when the parameters are not on separate lines.

Use spaces around the = operator when assigning default values to method parameters:

While several Ruby books suggest the first style, the second is much more prominent in practice (and arguably a bit more readable).

Avoid line continuation with \ where not required. In practice, avoid using line continuations for anything but string concatenation.

Adopt a consistent multi-line method chaining style. There are two popular styles in the Ruby community, both of which are considered good - leading . and trailing . .

When continuing a chained method call on another line, keep the . on the second line.

When continuing a chained method call on another line, include the . on the first line to indicate that the expression continues.

A discussion on the merits of both alternative styles can be found here .

Align the arguments of a method call if they span more than one line. When aligning arguments is not appropriate due to line-length constraints, single indent for the lines after the first is also acceptable.

Omit the outer braces around an implicit options hash.

Omit both the outer braces and parentheses for methods that are part of an internal DSL (e.g., Rake, Rails, RSpec).

Do not put a space between a method name and the opening parenthesis.

Do not put a space between a receiver name and the opening brackets.

Align the elements of array literals spanning multiple lines.

Naming Conventions

The only real difficulties in programming are cache invalidation and naming things.

Name identifiers in English.

Use snake_case for symbols, methods and variables.

Do not separate numbers from letters on symbols, methods and variables.

Use CapitalCase for classes and modules. (Keep acronyms like HTTP, RFC, XML uppercase).

Use snake_case for naming files, e.g. hello_world.rb .

Use snake_case for naming directories, e.g. lib/hello_world/hello_world.rb .

Aim to have just a single class/module per source file. Name the file name as the class/module, but replacing CapitalCase with snake_case .

Use SCREAMING_SNAKE_CASE for other constants (those that don’t refer to classes and modules).

The names of predicate methods (methods that return a boolean value) should end in a question mark (i.e. Array#empty? ). Methods that don’t return a boolean, shouldn’t end in a question mark.

Avoid prefixing predicate methods with the auxiliary verbs such as is , does , or can . These words are redundant and inconsistent with the style of boolean methods in the Ruby core library, such as empty? and include? .

The names of potentially dangerous methods (i.e. methods that modify self or the arguments, exit! (doesn’t run the finalizers like exit does), etc) should end with an exclamation mark if there exists a safe version of that dangerous method.

Define the non-bang (safe) method in terms of the bang (dangerous) one if possible.

Prefix with _ unused block parameters and local variables. It’s also acceptable to use just _ (although it’s a bit less descriptive). This convention is recognized by the Ruby interpreter and tools like RuboCop will suppress their unused variable warnings.

When defining binary operators and operator-alike methods, name the parameter other for operators with "symmetrical" semantics of operands. Symmetrical semantics means both sides of the operator are typically of the same or coercible types.

Operators and operator-alike methods with symmetrical semantics (the parameter should be named other ): `, `-`, ` + , / , % , * , == , > , < , | , & , ^ , eql? , equal? .

Operators with non-symmetrical semantics (the parameter should not be named other ): << , [] (collection/item relations between operands), === (pattern/matchable relations).

Note that the rule should be followed only if both sides of the operator have the same semantics. Prominent exception in Ruby core is, for example, Array#*(int) .

Flow of Control

Do not use for , unless you know exactly why. Most of the time iterators should be used instead. for is implemented in terms of each (so you’re adding a level of indirection), but with a twist - for doesn’t introduce a new scope (unlike each ) and variables defined in its block will be visible outside it.

Do not use then for multi-line if / unless / when / in .

Always put the condition on the same line as the if / unless in a multi-line conditional.

Prefer the ternary operator( ?: ) over if/then/else/end constructs. It’s more common and obviously more concise.

Use one expression per branch in a ternary operator. This also means that ternary operators must not be nested. Prefer if/else constructs in these cases.

Do not use if x; …​ . Use the ternary operator instead.

Prefer case over if-elsif when compared value is the same in each clause.

Leverage the fact that if and case are expressions which return a result.

Use when x then …​ for one-line cases.

Do not use when x; …​ . See the previous rule.

Do not use in pattern; …​ . Use in pattern then …​ for one-line in pattern branches.

Use ! instead of not .

Avoid unnecessary uses of !!

!! converts a value to boolean, but you don’t need this explicit conversion in the condition of a control expression; using it only obscures your intention.

Consider using it only when there is a valid reason to restrict the result true or false . Examples include outputting to a particular format or API like JSON, or as the return value of a predicate? method. In these cases, also consider doing a nil check instead: !something.nil? .

Do not use and and or in boolean context - and and or are control flow operators and should be used as such. They have very low precedence, and can be used as a short form of specifying flow sequences like "evaluate expression 1, and only if it is not successful (returned nil ), evaluate expression 2". This is especially useful for raising errors or early return without breaking the reading flow.

Avoid several control flow operators in one expression, as that quickly becomes confusing:

Simply put - because they add some cognitive overhead, as they don’t behave like similarly named logical operators in other languages.

First of all, and and or operators have lower precedence than the = operator, whereas the && and || operators have higher precedence than the = operator, based on order of operations.

Also && has higher precedence than || , where as and and or have the same one. Funny enough, even though and and or were inspired by Perl, they don’t have different precedence in Perl.

Avoid multi-line ?: (the ternary operator); use if / unless instead.

Prefer modifier if / unless usage when you have a single-line body. Another good alternative is the usage of control flow and / or .

Avoid modifier if / unless usage at the end of a non-trivial multi-line block.

Avoid nested modifier if / unless / while / until usage. Prefer && / || if appropriate.

Prefer unless over if for negative conditions (or control flow || ).

Do not use unless with else . Rewrite these with the positive case first.

Don’t use parentheses around the condition of a control expression.

Do not use while/until condition do for multi-line while/until .

Prefer modifier while/until usage when you have a single-line body.

Prefer until over while for negative conditions.

Use Kernel#loop instead of while / until when you need an infinite loop.

Use Kernel#loop with break rather than begin/end/until or begin/end/while for post-loop tests.

Avoid return where not required for flow of control.

Avoid self where not required. (It is only required when calling a self write accessor, methods named after reserved words, or overloadable operators.)

As a corollary, avoid shadowing methods with local variables unless they are both equivalent.

Don’t use the return value of = (an assignment) in conditional expressions unless the assignment is wrapped in parentheses. This is a fairly popular idiom among Rubyists that’s sometimes referred to as safe assignment in condition .

Avoid the use of BEGIN blocks.

Do not use END blocks. Use Kernel#at_exit instead.

Avoid use of nested conditionals for flow of control.

Prefer a guard clause when you can assert invalid data. A guard clause is a conditional statement at the top of a function that bails out as soon as it can.

Prefer next in loops instead of conditional blocks.

Prefer raise over fail for exceptions.

Don’t specify RuntimeError explicitly in the two argument version of raise .

Prefer supplying an exception class and a message as two separate arguments to raise , instead of an exception instance.

Do not return from an ensure block. If you explicitly return from a method inside an ensure block, the return will take precedence over any exception being raised, and the method will return as if no exception had been raised at all. In effect, the exception will be silently thrown away.

Use implicit begin blocks where possible.

Mitigate the proliferation of begin blocks by using contingency methods (a term coined by Avdi Grimm).

Don’t suppress exceptions.

Avoid using rescue in its modifier form.

Don’t use exceptions for flow of control.

Avoid rescuing the Exception class. This will trap signals and calls to exit , requiring you to kill -9 the process.

Put more specific exceptions higher up the rescue chain, otherwise they’ll never be rescued from.

Use the convenience methods File.read or File.binread when only reading a file start to finish in a single operation.

Use the convenience methods File.write or File.binwrite when only opening a file to create / replace its content in a single operation.

Release external resources obtained by your program in an ensure block.

Use versions of resource obtaining methods that do automatic resource cleanup when possible.

When doing file operations after confirming the existence check of a file, frequent parallel file operations may cause problems that are difficult to reproduce. Therefore, it is preferable to use atomic file operations.

Prefer the use of exceptions from the standard library over introducing new exception classes.

Assignment & Comparison

Avoid the use of parallel assignment for defining variables. Parallel assignment is allowed when it is the return of a method call (e.g. Hash#values_at ), used with the splat operator, or when used to swap variable assignment. Parallel assignment is less readable than separate assignment.

Use parallel assignment when swapping 2 values.

Avoid the use of unnecessary trailing underscore variables during parallel assignment. Named underscore variables are to be preferred over underscore variables because of the context that they provide. Trailing underscore variables are necessary when there is a splat variable defined on the left side of the assignment, and the splat variable is not an underscore.

Use shorthand self assignment operators whenever applicable.

Use ||= to initialize variables only if they’re not already initialized.

Use &&= to preprocess variables that may or may not exist. Using &&= will change the value only if it exists, removing the need to check its existence with if .

Prefer equal? over == when comparing object_id . Object#equal? is provided to compare objects for identity, and in contrast Object#== is provided for the purpose of doing value comparison.

Similarly, prefer using Hash#compare_by_identity than using object_id for keys:

Note that Set also has Set#compare_by_identity available.

Avoid explicit use of the case equality operator === . As its name implies it is meant to be used implicitly by case expressions and outside of them it yields some pretty confusing code.

Prefer is_a? over kind_of? . The two methods are synonyms, but is_a? is the more commonly used name in the wild.

Prefer is_a? over instance_of? .

While the two methods are similar, is_a? will consider the whole inheritance chain (superclasses and included modules), which is what you normally would want to do. instance_of? , on the other hand, only returns true if an object is an instance of that exact class you’re checking for, not a subclass.

Use Object#instance_of? instead of class comparison for equality.

Do not use eql? when using == will do. The stricter comparison semantics provided by eql? are rarely needed in practice.

Blocks, Procs & Lambdas

Use the Proc call shorthand when the called method is the only operation of a block.

Prefer {…​} over do…​end for single-line blocks. Avoid using {…​} for multi-line blocks (multi-line chaining is always ugly). Always use do…​end for "control flow" and "method definitions" (e.g. in Rakefiles and certain DSLs). Avoid do…​end when chaining.

Some will argue that multi-line chaining would look OK with the use of {…​}, but they should ask themselves - is this code really readable and can the blocks' contents be extracted into nifty methods?

Use multi-line do …​ end block instead of single-line do …​ end block.

Consider using explicit block argument to avoid writing block literal that just passes its arguments to another block.

Avoid comma after the last parameter in a block, except in cases where only a single argument is present and its removal would affect functionality (for instance, array destructuring).

Do not use nested method definitions, use lambda instead. Nested method definitions actually produce methods in the same scope (e.g. class) as the outer method. Furthermore, the "nested method" will be redefined every time the method containing its definition is called.

Use the new lambda literal syntax for single-line body blocks. Use the lambda method for multi-line blocks.

Don’t omit the parameter parentheses when defining a stabby lambda with parameters.

Omit the parameter parentheses when defining a stabby lambda with no parameters.

Prefer proc over Proc.new .

Prefer proc.call() over proc[] or proc.() for both lambdas and procs.

Avoid methods longer than 10 LOC (lines of code). Ideally, most methods will be shorter than 5 LOC. Empty lines do not contribute to the relevant LOC.

Avoid top-level method definitions. Organize them in modules, classes or structs instead.

Avoid single-line methods. Although they are somewhat popular in the wild, there are a few peculiarities about their definition syntax that make their use undesirable. At any rate - there should be no more than one expression in a single-line method.

One exception to the rule are empty-body methods.

Only use Ruby 3.0’s endless method definitions with a single line body. Ideally, such method definitions should be both simple (a single expression) and free of side effects.

Use :: only to reference constants (this includes classes and modules) and constructors (like Array() or Nokogiri::HTML() ). Do not use :: for regular method calls.

Do not use :: to define class methods.

Use def with parentheses when there are parameters. Omit the parentheses when the method doesn’t accept any parameters.

Use parentheses around the arguments of method calls, especially if the first argument begins with an open parenthesis ( , as in f((3 + 2) + 1) .

Method Call with No Arguments

Always omit parentheses for method calls with no arguments.

Methods That Have "keyword" Status in Ruby

Always omit parentheses for methods that have "keyword" status in Ruby.

Non-Declarative Methods That Have "keyword" Status in Ruby

For non-declarative methods with "keyword" status (e.g., various Kernel instance methods), two styles are considered acceptable. By far the most popular style is to omit parentheses. Rationale: The code reads better, and method calls look more like keywords. A less-popular style, but still acceptable, is to include parentheses. Rationale: The methods have ordinary semantics, so why treat them differently, and it’s easier to achieve a uniform style by not worrying about which methods have "keyword" status. Whichever one you pick, apply it consistently.

Using super with Arguments

Always use parentheses when calling super with arguments:

Avoid parameter lists longer than three or four parameters.

Define optional arguments at the end of the list of arguments. Ruby has some unexpected results when calling methods that have optional arguments at the front of the list.

Put required keyword arguments before optional keyword arguments. Otherwise, it’s much harder to spot optional keyword arguments there, if they’re hidden somewhere in the middle.

Use keyword arguments when passing a boolean argument to a method.

Prefer keyword arguments over optional arguments.

Use keyword arguments instead of option hashes.

Use Ruby 2.7’s arguments forwarding.

Use Ruby 3.1’s anonymous block forwarding.

In most cases, block argument is given name similar to &block or &proc . Their names have no information and & will be sufficient for syntactic meaning.

If you really need "global" methods, add them to Kernel and make them private.

Classes & Modules

Use a consistent structure in your class definitions.

Split multiple mixins into separate statements.

Prefer a two-line format for class definitions with no body. It is easiest to read, understand, and modify.

Don’t nest multi-line classes within classes. Try to have such nested classes each in their own file in a folder named like the containing class.

Define (and reopen) namespaced classes and modules using explicit nesting. Using the scope resolution operator can lead to surprising constant lookups due to Ruby’s lexical scoping , which depends on the module nesting at the point of definition.

Prefer modules to classes with only class methods. Classes should be used only when it makes sense to create instances out of them.

Prefer the use of module_function over extend self when you want to turn a module’s instance methods into class methods.

When designing class hierarchies make sure that they conform to the Liskov Substitution Principle .

Try to make your classes as SOLID as possible.

Always supply a proper to_s method for classes that represent domain objects.

Use the attr family of functions to define trivial accessors or mutators.

For accessors and mutators, avoid prefixing method names with get_ and set_ . It is a Ruby convention to use attribute names for accessors (readers) and attr_name= for mutators (writers).

Avoid the use of attr . Use attr_reader and attr_accessor instead.

Consider using Struct.new , which defines the trivial accessors, constructor and comparison operators for you.

Don’t extend an instance initialized by Struct.new . Extending it introduces a superfluous class level and may also introduce weird errors if the file is required multiple times.

Don’t extend an instance initialized by Data.define . Extending it introduces a superfluous class level.

Prefer duck-typing over inheritance.

Avoid the usage of class ( @@ ) variables due to their "nasty" behavior in inheritance.

As you can see all the classes in a class hierarchy actually share one class variable. Class instance variables should usually be preferred over class variables.

Assign proper visibility levels to methods ( private , protected ) in accordance with their intended usage. Don’t go off leaving everything public (which is the default).

Indent the public , protected , and private methods as much as the method definitions they apply to. Leave one blank line above the visibility modifier and one blank line below in order to emphasize that it applies to all methods below it.

Use def self.method to define class methods. This makes the code easier to refactor since the class name is not repeated.

Prefer alias when aliasing methods in lexical class scope as the resolution of self in this context is also lexical, and it communicates clearly to the user that the indirection of your alias will not be altered at runtime or by any subclass unless made explicit.

Since alias , like def , is a keyword, prefer bareword arguments over symbols or strings. In other words, do alias foo bar , not alias :foo :bar .

Also be aware of how Ruby handles aliases and inheritance: an alias references the method that was resolved at the time the alias was defined; it is not dispatched dynamically.

In this example, Fugitive#given_name would still call the original Westerner#first_name method, not Fugitive#first_name . To override the behavior of Fugitive#given_name as well, you’d have to redefine it in the derived class.

Always use alias_method when aliasing methods of modules, classes, or singleton classes at runtime, as the lexical scope of alias leads to unpredictability in these cases.

When class (or module) methods call other such methods, omit the use of a leading self or own name followed by a . when calling other such methods. This is often seen in "service classes" or other similar concepts where a class is treated as though it were a function. This convention tends to reduce repetitive boilerplate in such classes.

Do not define constants within a block, since the block’s scope does not isolate or namespace the constant in any way.

Define the constant outside of the block instead, or use a variable or method if defining the constant in the outer scope would be problematic.

Classes: Constructors

Consider adding factory methods to provide additional sensible ways to create instances of a particular class.

In constructors, avoid unnecessary disjunctive assignment ( ||= ) of instance variables. Prefer plain assignment. In ruby, instance variables (beginning with an @ ) are nil until assigned a value, so in most cases the disjunction is unnecessary.

Good code is its own best documentation. As you’re about to add a comment, ask yourself, "How can I improve the code so that this comment isn’t needed?". Improve the code and then document it to make it even clearer.

Write self-documenting code and ignore the rest of this section. Seriously!

If the how can be made self-documenting, but not the why (e.g. the code works around non-obvious library behavior, or implements an algorithm from an academic paper), add a comment explaining the rationale behind the code.

Write comments in English.

Use one space between the leading # character of the comment and the text of the comment.

Comments longer than a word are capitalized and use punctuation. Use one space after periods.

Avoid superfluous comments.

Keep existing comments up-to-date. An outdated comment is worse than no comment at all.

Good code is like a good joke: it needs no explanation.

Avoid writing comments to explain bad code. Refactor the code to make it self-explanatory. ("Do or do not - there is no try." Yoda)

Comment Annotations

Annotations should usually be written on the line immediately above the relevant code.

The annotation keyword is followed by a colon and a space, then a note describing the problem.

If multiple lines are required to describe the problem, subsequent lines should be indented three spaces after the # (one general plus two for indentation purposes).

In cases where the problem is so obvious that any documentation would be redundant, annotations may be left at the end of the offending line with no note. This usage should be the exception and not the rule.

Use TODO to note missing features or functionality that should be added at a later date.

Use FIXME to note broken code that needs to be fixed.

Use OPTIMIZE to note slow or inefficient code that may cause performance problems.

Use HACK to note code smells where questionable coding practices were used and should be refactored away.

Use REVIEW to note anything that should be looked at to confirm it is working as intended. For example: REVIEW: Are we sure this is how the client does X currently?

Use other custom annotation keywords if it feels appropriate, but be sure to document them in your project’s README or similar.

Magic Comments

Place magic comments above all code and documentation in a file (except shebangs, which are discussed next).

Place magic comments below shebangs when they are present in a file.

Use one magic comment per line if you need multiple.

Separate magic comments from code and documentation with a blank line.

Collections

Prefer literal array and hash creation notation (unless you need to pass parameters to their constructors, that is).

Prefer %w to the literal array syntax when you need an array of words (non-empty strings without spaces and special characters in them). Apply this rule only to arrays with two or more elements.

Prefer %i to the literal array syntax when you need an array of symbols (and you don’t need to maintain Ruby 1.9 compatibility). Apply this rule only to arrays with two or more elements.

Avoid comma after the last item of an Array or Hash literal, especially when the items are not on separate lines.

Avoid the creation of huge gaps in arrays.

When accessing the first or last element from an array, prefer first or last over [0] or [-1] . first and last take less effort to understand, especially for a less experienced Ruby programmer or someone from a language with different indexing semantics.

Use Set instead of Array when dealing with unique elements. Set implements a collection of unordered values with no duplicates. This is a hybrid of Array 's intuitive inter-operation facilities and Hash 's fast lookup.

Prefer symbols instead of strings as hash keys.

Avoid the use of mutable objects as hash keys.

Use the Ruby 1.9 hash literal syntax when your hash keys are symbols.

Use the Ruby 3.1 hash literal value syntax when your hash key and value are the same.

Wrap hash literal in braces if it is a last array item.

Don’t mix the Ruby 1.9 hash syntax with hash rockets in the same hash literal. When you’ve got keys that are not symbols stick to the hash rockets syntax.

Hash::[] was a pre-Ruby 2.1 way of constructing hashes from arrays of key-value pairs, or from a flat list of keys and values. It has an obscure semantic and looks cryptic in code. Since Ruby 2.1, Enumerable#to_h can be used to construct a hash from a list of key-value pairs, and it should be preferred. Instead of Hash[] with a list of literal keys and values, just a hash literal should be preferred.

Use Hash#key? instead of Hash#has_key? and Hash#value? instead of Hash#has_value? .

Use Hash#each_key instead of Hash#keys.each and Hash#each_value instead of Hash#values.each .

Use Hash#fetch when dealing with hash keys that should be present.

Introduce default values for hash keys via Hash#fetch as opposed to using custom logic.

Prefer the use of the block instead of the default value in Hash#fetch if the code that has to be evaluated may have side effects or be expensive.

Use Hash#values_at or Hash#fetch_values when you need to retrieve several values consecutively from a hash.

Prefer transform_keys or transform_values over each_with_object or map when transforming just the keys or just the values of a hash.

Rely on the fact that as of Ruby 1.9 hashes are ordered.

Do not modify a collection while traversing it.

When accessing elements of a collection, avoid direct access via [n] by using an alternate form of the reader method if it is supplied. This guards you from calling [] on nil .

When providing an accessor for a collection, provide an alternate form to save users from checking for nil before accessing an element in the collection.

Prefer map over collect , find over detect , select over find_all , reduce over inject , include? over member? and size over length . This is not a hard requirement; if the use of the alias enhances readability, it’s ok to use it. The rhyming methods are inherited from Smalltalk and are not common in other programming languages. The reason the use of select is encouraged over find_all is that it goes together nicely with reject and its name is pretty self-explanatory.

Don’t use count as a substitute for size . For Enumerable objects other than Array it will iterate the entire collection in order to determine its size.

Use flat_map instead of map + flatten . This does not apply for arrays with a depth greater than 2, i.e. if users.first.songs == ['a', ['b','c']] , then use map + flatten rather than flat_map . flat_map flattens the array by 1, whereas flatten flattens it all the way.

Prefer reverse_each to reverse.each because some classes that include Enumerable will provide an efficient implementation. Even in the worst case where a class does not provide a specialized implementation, the general implementation inherited from Enumerable will be at least as efficient as using reverse.each .

The method Object#then is preferred over Object#yield_self , since the name then states the intention, not the behavior. This makes the resulting code easier to read.

Slicing arrays with ranges to extract some of their elements (e.g ary[2..5] ) is a popular technique. Below you’ll find a few small considerations to keep in mind when using it.

[0..-1] in ary[0..-1] is redundant and simply synonymous with ary .

Ruby 2.6 introduced endless ranges, which provide an easier way to describe a slice going all the way to the end of an array.

Ruby 2.7 introduced beginless ranges, which are also handy in slicing. However, unlike the somewhat obscure -1 in ary[1..-1] , the 0 in ary[0..42] is clear as a starting point. In fact, changing it to ary[..42] could potentially make it less readable. Therefore, using code like ary[0..42] is fine. On the other hand, ary[nil..42] should be replaced with ary[..42] or arr[0..42] .

Add underscores to large numeric literals to improve their readability.

Prefer lowercase letters for numeric literal prefixes. 0o for octal, 0x for hexadecimal and 0b for binary. Do not use 0d prefix for decimal literals.

Use Integer to check the type of an integer number. Since Fixnum is platform-dependent, checking against it will return different results on 32-bit and 64-bit machines.

Prefer to use ranges when generating random numbers instead of integers with offsets, since it clearly states your intentions. Imagine simulating a roll of a dice:

When performing float-division on two integers, either use fdiv or convert one-side integer to float.

Avoid (in)equality comparisons of floats as they are unreliable.

Floating point values are inherently inaccurate, and comparing them for exact equality is almost never the desired semantics. Comparison via the ==/!= operators checks floating-point value representation to be exactly the same, which is very unlikely if you perform any arithmetic operations involving precision loss.

When using exponential notation for numbers, prefer using the normalized scientific notation, which uses a mantissa between 1 (inclusive) and 10 (exclusive). Omit the exponent altogether if it is zero.

The goal is to avoid confusion between powers of ten and exponential notation, as one quickly reading 10e7 could think it’s 10 to the power of 7 (one then 7 zeroes) when it’s actually 10 to the power of 8 (one then 8 zeroes). If you want 10 to the power of 7, you should do 1e7 .

One could favor the alternative engineering notation, in which the exponent must always be a multiple of 3 for easy conversion to the thousand / million / …​ system.

Alternative : engineering notation:

Prefer string interpolation and string formatting to string concatenation:

Adopt a consistent string literal quoting style. There are two popular styles in the Ruby community, both of which are considered good - single quotes by default and double quotes by default.

Single Quote

Prefer single-quoted strings when you don’t need string interpolation or special symbols such as \t , \n , ' , etc.

Double Quote

Prefer double-quotes unless your string literal contains " or escape characters you want to suppress.

Don’t use the character literal syntax ?x . Since Ruby 1.9 it’s basically redundant - ?x would be interpreted as 'x' (a string with a single character in it).

Don’t leave out {} around instance and global variables being interpolated into a string.

Don’t use Object#to_s on interpolated objects. It’s called on them automatically.

Avoid using String#` when you need to construct large data chunks. Instead, use `String#<<`. Concatenation mutates the string instance in-place and is always faster than `String# , which creates a bunch of new string objects.

Don’t use String#gsub in scenarios in which you can use a faster and more specialized alternative.

Prefer the use of String#chars over String#split with empty string or regexp literal argument.

Prefer the use of sprintf and its alias format over the fairly cryptic String#% method.

When using named format string tokens, favor %<name>s over %{name} because it encodes information about the type of the value.

Break long strings into multiple lines but don’t concatenate them with + . If you want to add newlines, use heredoc. Otherwise use \ :

Use Ruby 2.3’s squiggly heredocs for nicely indented multi-line strings.

Use descriptive delimiters for heredocs. Delimiters add valuable information about the heredoc content, and as an added bonus some editors can highlight code within heredocs if the correct delimiter is used.

Place method calls with heredoc receivers on the first line of the heredoc definition. The bad form has significant potential for error if a new line is added or removed.

Place the closing parenthesis for method calls with heredoc arguments on the first line of the heredoc definition. The bad form has potential for error if the new line before the closing parenthesis is removed.

Date & Time

Prefer Time.now over Time.new when retrieving the current system time.

Don’t use DateTime unless you need to account for historical calendar reform - and if you do, explicitly specify the start argument to clearly state your intentions.

Regular Expressions

Some people, when confronted with a problem, think "I know, I’ll use regular expressions." Now they have two problems.

Don’t use regular expressions if you just need plain text search in string.

For simple constructions you can use regexp directly through string index.

Use non-capturing groups when you don’t use the captured result.

Do not mix named captures and numbered captures in a Regexp literal. Because numbered capture is ignored if they’re mixed.

Prefer using names to refer named regexp captures instead of numbers.

Don’t use the cryptic Perl-legacy variables denoting last regexp group matches ( $1 , $2 , etc). Use Regexp.last_match(n) instead.

Avoid using numbered groups as it can be hard to track what they contain. Named groups can be used instead.

Character classes have only a few special characters you should care about: ^ , - , \ , ] , so don’t escape . or brackets in [] .

Be careful with ^ and $ as they match start/end of line, not string endings. If you want to match the whole string use: \A and \z (not to be confused with \Z which is the equivalent of /\n?\z/ ).

Use x (free-spacing) modifier for multi-line regexps.

Use x modifier for complex regexps. This makes them more readable and you can add some useful comments.

For complex replacements sub / gsub can be used with a block or a hash.

Percent Literals

Use %() (it’s a shorthand for %Q ) for single-line strings which require both interpolation and embedded double-quotes. For multi-line strings, prefer heredocs.

Avoid %() or the equivalent %q() unless you have a string with both ' and " in it. Regular string literals are more readable and should be preferred unless a lot of characters would have to be escaped in them.

Use %r only for regular expressions matching at least one / character.

Avoid the use of %x unless you’re going to execute a command with backquotes in it (which is rather unlikely).

Avoid the use of %s . It seems that the community has decided :"some string" is the preferred way to create a symbol with spaces in it.

Use the braces that are the most appropriate for the various kinds of percent literals.

() for string literals ( %q , %Q ).

[] for array literals ( %w , %i , %W , %I ) as it is aligned with the standard array literals.

{} for regexp literals ( %r ) since parentheses often appear inside regular expressions. That’s why a less common character with { is usually the best delimiter for %r literals.

() for all other literals (e.g. %s , %x )

Metaprogramming

Avoid needless metaprogramming.

Do not mess around in core classes when writing libraries (do not monkey-patch them).

The block form of class_eval is preferable to the string-interpolated form.

Supply Location

When you use the string-interpolated form, always supply __FILE__ and __LINE__ , so that your backtraces make sense:

define_method

define_method is preferable to class_eval { def …​ }

When using class_eval (or other eval ) with string interpolation, add a comment block showing its appearance if interpolated (a practice used in Rails code):

Avoid using method_missing for metaprogramming because backtraces become messy, the behavior is not listed in #methods , and misspelled method calls might silently work, e.g. nukes.luanch_state = false . Consider using delegation, proxy, or define_method instead. If you must use method_missing :

Be sure to also define respond_to_missing?

Only catch methods with a well-defined prefix, such as find_by_* --make your code as assertive as possible.

Call super at the end of your statement

Delegate to assertive, non-magical methods:

Prefer public_send over send so as not to circumvent private / protected visibility.

Prefer __send__ over send , as send may overlap with existing methods.

API Documentation

Use YARD and its conventions for API documentation.

Don’t use block comments. They cannot be preceded by whitespace and are not as easy to spot as regular comments.

This is not really a block comment syntax, but more of an attempt to emulate Perl’s POD documentation system.

There’s an rdtool for Ruby that’s pretty similar to POD. Basically rdtool scans a file for =begin and =end pairs, and extracts the text between them all. This text is assumed to be documentation in RD format . You can read more about it here .

RD predated the rise of RDoc and YARD and was effectively obsoleted by them. [ 3 ]

Gemfile and Gemspec

The gemspec should not contain RUBY_VERSION as a condition to switch dependencies. RUBY_VERSION is determined by rake release , so users may end up with wrong dependency.

Fix by either:

Post-install messages.

Add both gems as dependency (if permissible).

If development dependencies, move to Gemfile.

Avoid the use of flip-flop operators .

Don’t do explicit non- nil checks unless you’re dealing with boolean values.

Use $stdout/$stderr/$stdin instead of STDOUT/STDERR/STDIN . STDOUT/STDERR/STDIN are constants, and while you can actually reassign (possibly to redirect some stream) constants in Ruby, you’ll get an interpreter warning if you do so.

Use warn instead of $stderr.puts . Apart from being more concise and clear, warn allows you to suppress warnings if you need to (by setting the warn level to 0 via -W0 ).

Prefer the use of Array#join over the fairly cryptic Array#* with a string argument.

Use Array() instead of explicit Array check or [*var] , when dealing with a variable you want to treat as an Array, but you’re not certain it’s an array.

Use ranges or Comparable#between? instead of complex comparison logic when possible.

Prefer the use of predicate methods to explicit comparisons with == . Numeric comparisons are OK.

Avoid using Perl-style special variables (like $: , $; , etc). They are quite cryptic and their use in anything but one-liner scripts is discouraged.

Use the human-friendly aliases provided by the English library if required.

For all your internal dependencies, you should use require_relative . Use of require should be reserved for external dependencies

This way is more expressive (making clear which dependency is internal or not) and more efficient (as require_relative doesn’t have to try all of $LOAD_PATH contrary to require ).

Write ruby -w safe code.

Avoid hashes as optional parameters. Does the method do too much? (Object initializers are exceptions for this rule).

Use module instance variables instead of global variables.

Use OptionParser for parsing complex command line options and ruby -s for trivial command line options.

Do not mutate parameters unless that is the purpose of the method.

Avoid more than three levels of block nesting.

Code in a functional way, avoiding mutation when that makes sense.

Omit the .rb extension for filename passed to require and require_relative .

The method tap can be helpful for debugging purposes but should not be left in production code.

This is simpler and more efficient.

Here are some tools to help you automatically check Ruby code against this guide.

RuboCop is a Ruby static code analyzer and formatter, based on this style guide. RuboCop already covers a significant portion of the guide and has plugins for most popular Ruby editors and IDEs.

RubyMine 's code inspections are partially based on this guide.

This guide started its life in 2011 as an internal company Ruby coding guidelines (written by Bozhidar Batsov ). Bozhidar had always been bothered as a Ruby developer about one thing - Python developers had a great programming style reference ( PEP-8 ) and Rubyists never got an official guide, documenting Ruby coding style and best practices. Bozhidar firmly believed that style matters. He also believed that a great hacker community, such as Ruby has, should be quite capable of producing this coveted document. The rest is history…​

At some point Bozhidar decided that the work he was doing might be interesting to members of the Ruby community in general and that the world had little need for another internal company guideline. But the world could certainly benefit from a community-driven and community-sanctioned set of practices, idioms and style prescriptions for Ruby programming.

Bozhidar served as the guide’s only editor for a few years, before a team of editors was formed once the project transitioned to RuboCop HQ.

Since the inception of the guide we’ve received a lot of feedback from members of the exceptional Ruby community around the world. Thanks for all the suggestions and the support! Together we can make a resource beneficial to each and every Ruby developer out there.

Many people, books, presentations, articles and other style guides influenced the community Ruby style guide. Here are some of them:

"The Elements of Style"

"The Elements of Programming Style"

The Python Style Guide (PEP-8)

"Programming Ruby"

"The Ruby Programming Language"

Contributing

The guide is still a work in progress - some guidelines are lacking examples, some guidelines don’t have examples that illustrate them clearly enough. Improving such guidelines is a great (and simple way) to help the Ruby community!

In due time these issues will (hopefully) be addressed - just keep them in mind for now.

Nothing written in this guide is set in stone. It’s our desire to work together with everyone interested in Ruby coding style, so that we could ultimately create a resource that will be beneficial to the entire Ruby community.

Feel free to open tickets or send pull requests with improvements. Thanks in advance for your help!

You can also support the project (and RuboCop) with financial contributions via one of the following platforms:

GitHub Sponsors

It’s easy, just follow the contribution guidelines below:

Fork rubocop/ruby-style-guide on GitHub

Make your feature addition or bug fix in a feature branch.

Include a good description of your changes

Push your feature branch to GitHub

Send a Pull Request

This guide is written in AsciiDoc and is published as HTML using AsciiDoctor . The HTML version of the guide is hosted on GitHub Pages.

Originally the guide was written in Markdown, but was converted to AsciiDoc in 2019.

Creative Commons License

A community-driven style guide is of little use to a community that doesn’t know about its existence. Tweet about the guide, share it with your friends and colleagues. Every comment, suggestion or opinion we get makes the guide just a little bit better. And we want to have the best possible guide, don’t we?

U.S. flag

An official website of the United States government

Consumer Safety Inspector

Department of agriculture, circuit - sacramento, ca.

$5,000 Sign on Bonus, Creditable Service for Annual Leave Accrual, Public Service Loan Forgiveness , and Referral Bonus Awards are available. Click Learn more about this agency below. Shifts and species will vary based on assignment. For additional information contact the Alameda District -Sandy Cai @ [email protected] or Tutu Sidhu @ [email protected] Employee may be detailed to any shift at any plant in the Alameda District.

  • Accepting applications

Open & closing dates

05/21/2024 to 05/28/2024

$39,576 - $77,955 per year

Pay scale & grade

1 vacancy in the following location:

  • Anderson, CA

Telework eligible

Travel required.

Occasional travel - You may be expected to travel for this position.

Relocation expenses reimbursed

Appointment type, work schedule.

Competitive

Promotion potential

Job family (series).

1862 Consumer Safety Inspection

Supervisory status

Security clearance, position sensitivity and risk.

Non-sensitive (NS)/Low Risk

Trust determination process

Suitability/Fitness

Announcement number

FSIS-24-MCE-12420935-MS

Control number

This job is open to, career transition (ctap, ictap, rpl).

Federal employees who meet the definition of a "surplus" or "displaced" employee.

U.S. Citizens, Nationals or those who owe allegiance to the U.S.

  • YOU WILL/MAY:
  • Ensure that regulated establishments produce a safe product by executing appropriate inspection methods, determining non-compliance with regulatory requirements, documenting noncompliance and initiating enforcement action, where warranted.
  • Verify that meat and poultry slaughter and/or processing establishment's Sanitation Standard Operating Procedures (SSOP) and Hazard Analysis and Critical Control Point (HACCP) Plans meet regulatory requirements.
  • Execute Sanitation Standard Operating Procedures (SSOP) and Hazard Analysis and Critical Control Point (HACCP) Plans effectively to prevent unsanitary conditions and adulteration of product.
  • Review records, observe plant operations and conduct hands-on verification to ensure compliance with regulatory requirements and prepare detailed documentation (Non-Compliance Records) of non-compliance with regulatory requirements.
  • Determine when regulatory control action is necessary. You will assess whether the plant's corrective or preventative actions are acceptable and effective, if there are trends in non-compliance, or if enforcement action is warranted.
  • Conduct regulatory oversight activities inside plants in matters relating to other consumer protections (e.g., economic adulteration and misbranding).
  • Have contact with plant managers, owners and others to explain legal and regulatory requirements, discuss operation of the plant's SSOP, HACCP plan and other food safety programs.
  • Communicate and defend determinations on non-compliance issues and discuss plans for addressing non-compliance.
  • Work with a variety of individuals to resolve problems, clarify differences of interpretation concerning HACCP and other food safety or consumer protection requirements.
  • Advise other Agency inspectors, supervisors and officers on inspection and enforcement matters for which you are involved.
  • Conduct various samplings, surveys and tests to obtain pertinent data on potential problem areas, industry trends, or other issues of current interest to the Agency.
  • Be involved in performing health and safety verification sampling and tests for detection of specific microbes (e.g., salmonella, listeria, etc.), residues or contaminants.
  • Assure that products approved for import are in full compliance with all applicable Federal regulations governing the importation of meat and poultry products.
  • Authorize entry of all meat or poultry products considered to comply with Federal regulations or refuse entry of any products which violate any of the requirements for admission into this country.
  • Coordinate with other Federal agencies (e.g., the Animal and Plant Health Inspection Service (APHIS) and U.S. Customs and Border Protection (CBP) on such matters as animal health restrictions and refused entry lots.

Requirements

Conditions of employment.

  • Training as a condition of employment (TCOE) is required. You must begin the training within 90 days of the effective date of your selection, and you must successfully complete it within 12 months of the effective date of your selection.
  • Subject to satisfactory adjudication of background investigation and/or fingerprint check.
  • Selectee may be subject to satisfactory completion of one-year probationary or trial period.
  • U.S. Citizenship required.
  • Successful completion of a pre-employment medical examination.
  • Male applicants born after December 31, 1959, must complete a Pre-Employment Certification Statement for Selective Service Registration.
  • Must be at least 18 years of age.
  • If you are newly hired, the documentation you present for purposes of completing the Department Homeland Security (DHS) Form I-9 on your entry-on-duty date will be verified through the DHS "E-VERIFY" system.
  • Must pass the E-Verify employment verification check. To learn more, including your rights and responsibilities, visit E-Verify at https://www.e-verify.gov/
  • If you are selected, you may need to complete a Declaration for Federal Employment (OF-306) prior to being appointed to determine suitability for Federal employment and to authorize a background investigation.
  • False statements or responses on a resume or application can jeopardize employment and may be grounds for disciplinary action, including removal from Federal service.
  • Direct Deposit - Per Public Law 104-134 every Federal employee is required to have federal payments made by direct deposit to a financial institution of that employee's choosing.
  • Should be able to read, speak, write, and effectively communicate in the English language.
  • This is a Bargaining Unit position covered by the National Joint Council (NJC) of Food Inspection Locals.

Qualifications

  • Skill in applying proper techniques for collecting samples and performing field tests and examinations,
  • Skill in developing written reports and reporting findings or results orally,
  • Skill in maintaining effective personal contacts with a variety of individuals.
  • Be physically and medically able to efficiently perform the essential job functions, without being a direct threat to themselves and others.
  • Have full range of motion to perform rapid repetitive twisting and working with arms above shoulder level.
  • Be able to stand and walk on slippery and uneven floors and catwalks, and climbing stairs and ladders.
  • Be able to lift, carry, push and pull up to 30 pounds, with occasional lifting of up to 50 pounds.
  • Have manual dexterity of the upper body, including arms, hands, and fingers with a normal sense of touch in both hands.
  • Have good near and distance vision, be free of chronic eye disease and have correctable vision of at least 20/40 in one eye.
  • Have the ability to distinguish shades of color. Any significant degree of color blindness (more than 25 percent error rate on approved color plate test) may be disqualifying.
  • Individuals with some hearing loss and/or requiring hearing amplification will be assessed on a case-by-case basis.

Education may be used to qualify in lieu of specialized experience as described below. For the GS-05 level: Successful completion of a full 4-year course of study leading to a bachelor's degree with major study or at least 24 semester hours/credits in any combination of coursework in the areas of: agricultural, biological, or physical sciences, food technology, epidemiology, home economics, pharmacy, engineering, or nutrition. Specialized government or military training may be creditable if it is related directly to this position. OR A combination of education and specialized experience. In this instance, only education in excess of the first 60 semester hours of a course of study leading to a bachelor's degree (with some related coursework, as described in number 2 above) is creditable towards meeting the requirements, along with specialized work experience. The combination must equal 100% of the requirement. For example, if you have 33% of the education requirement, then you will need 67% of the specialized experience requirement. For the GS-07 Level: One full year of directly related graduate education is qualifying for GS-7. OR A combination of education and specialized experience. In this instance, only graduate education directly related to the work of the position is creditable towards meeting the requirements, along with specialized work experience. The combination must equal 100% of the requirement. For example, if you have 33% of the education requirement, then you will need 67% of the specialized experience requirement. For the GS-09 Level: Two full years of directly related graduate education or a directly related master's degree is qualifying for GS-9. OR A combination of education and specialized experience. In this instance, only graduate education in excess of the first 18 semester hours directly related to the work of the position is creditable towards meeting the requirements, along with specialized work experience. The combination must equal 100% of the requirement. For example, if you have 33% of the education requirement, then you will need 67% of the specialized experience requirement.

Additional information

THIS POSITION REQUIRES A PRE-EMPLOYMENT PHYSICAL: Position Requirements . Assignment Restrictions: FSIS Directive 4735.9, Office of Field Operations Assignment Restrictions and Rules on Gifts from Regulated Industry FSIS Directive 4735.9 Revision 2 (usda.gov) , sets out the Agency's specific procedures regarding ethical employee conduct related to employee assignment restrictions and gifts from regulated establishments. Please click on this link and read directive prior to applying. Recruitment incentives are offered based on agency staffing needs and budgetary availability; service agreements apply . For detailed incentive information see: Career Profiles | FSIS . FSIS is pleased to offer a $5,000 sign on bonus paid out in one lump sum payment. This recruitment incentive requires a signed two-year service agreement, as well as satisfactory performance and conduct. The service agreement details conditions of receipt and acceptance of the incentive and is provided to new employees prior to entrance on duty. Funds will be collected for any periods of uncompleted service. Selectees may be eligible for Creditable Service for Annual Leave Accrual (CSALA) Public Service Loan Forgiveness Program. For more information please visit: PSLF Program . The position advertised offer a referral bonus award of $1,000. More than one award may be given subject to criteria being met. Current FSIS employees may be eligible for this award if they refer an applicant who later enters on duty and works at least 90 days with successful performance and conduct. The referred employee will have an opportunity to list the referring employee during the application process. There are some required restrictions on this award. Ineligible employees include: 1. Employees whose regular, recurring jobs include the recruitment of new employees. 2. Employees who are otherwise excluded from receiving Achievement Awards; 3. Selecting officials or other persons associated with the selection process of the referred employee; and 4. Any of the following relatives of the referred employee: Spouse, or parents thereof; Children, including stepchildren and adopted children, and spouses thereof; Parents, including stepparents; Siblings, including stepsiblings, and spouses thereof; Any individual related by blood or affinity whose close association with the employee is the equivalent of a family relationship.

A career with the U.S. government provides employees with a comprehensive benefits package. As a federal employee, you and your family will have access to a range of benefits that are designed to make your federal career very rewarding. Opens in a new window Learn more about federal benefits .

Review our benefits

Eligibility for benefits depends on the type of position you hold and whether your position is full-time, part-time or intermittent. Contact the hiring agency for more information on the specific benefits offered.

How You Will Be Evaluated

You will be evaluated for this job based on how well you meet the qualifications above.

  • Attention to Detail
  • Decision Making
  • Dependability
  • Flexibility
  • Interpersonal Skills
  • Self Management

As a new or existing federal employee, you and your family may have access to a range of benefits. Your benefits depend on the type of position you have - whether you're a permanent, part-time, temporary or an intermittent employee. You may be eligible for the following benefits, however, check with your agency to make sure you're eligible under their policies.

  • Your application may be disqualified if you include any of the information listed here: What should I leave out of my resume?

If you are relying on your education to meet qualification requirements:

Education must be accredited by an accrediting institution recognized by the U.S. Department of Education in order for it to be credited towards qualifications. Therefore, provide only the attendance and/or degrees from schools accredited by accrediting institutions recognized by the U.S. Department of Education .

Failure to provide all of the required information as stated in this vacancy announcement may result in an ineligible rating or may affect the overall rating.

Please read the entire announcement and all instructions before you begin. You must complete this application process and submit all required documents electronically by 11:59 p.m. Eastern Time (ET) on the closing date of this announcement. Applying online is highly encouraged. We are available to assist you during business hours (normally 8:00 a.m. - 4:00 p.m., Monday - Friday). If applying online poses a hardship, contact the Agency Contact listed below well before the closing date for an alternate method. All hardship application packages must be complete and submitted no later than noon ET on the closing date of the announcement to be entered into the system prior to its closing. This agency provides reasonable accommodation to applicants with disabilities on a case-by-case basis. Please contact us if you require this for any part of the application and hiring process. To begin, click "Apply Online" and follow the instructions to complete the Assessment Questionnaire and attach your resume and all required documents. Step 1: Create a USAJOBS account (if you do not already have one) at www.usajobs.gov . It is recommended that as part of your profile you set up automatic email notification to be informed when the status of your application changes. If you choose not to set up this automatic notification, then you will have to log into your USAJOBS account to check on the status of your application. Step 2: In your USAJOBS account, you will have the opportunity to select your stored USAJOBS resume, create a new resume or upload a resume, and upload other relevant documents. All uploaded documents must be less than 5MB and in one of the following document formats: GIF, JPG, JPEG, PNG, RTF, PDF, or Word (DOC or DOCX). See "Required Documents" for details. Select the document you want to submit. Step 3: Click "Apply Online," answer all required questions, verify the documents you selected from USAJOBS transferred into the Agency's staffing system, and attach any additional documents that may not have transferred or be required. If qualifying based on education, you must submit a legible copy of your college transcript(s), with your application package, showing your conferred degree (if any) and/or applicable coursework as proof that you qualify based on education. If you have not yet graduated, submit your current transcript. NOTE: It is an applicant's responsibility to submit updated information. You can update your application or documents anytime while the announcement is open. Simply log into your USAJOBS account and click on "Application Status." Click on the position title, and then select "Update Application" to continue. NOTE: Please verify that documents you are uploading from USAJOBs transfer into the Agency's staffing system as there is a limitation to the number of documents that can be transferred. However, once in the Agency's staffing system, you will have the opportunity to upload additional documents. Uploaded documents must be less than 5MB and in one of the following document formats: GIF, JPG, JPEG, PNG, RTF, PDF, TXT or Word (DOC or DOCX). Do not upload Adobe Portfolio documents because they are not viewable. If you do not have access to the Internet, you are strongly encouraged to visit your library, state employment office, or another establishment that provides internet service to complete the online application and the assessment questionnaire. If this is not an option, refer to the Alternative Methods for Applying section below for specific instructions. Alternative Methods for Applying: If you are unable to apply using the internet, please fax your request for an application package along with your name and mailing address to: HR (Branch 1) 1-833-840-9220,

Agency contact information

Merri stellburg.

612-852-7655

[email protected]

Your application will be reviewed to verify that you meet the eligibility and qualification requirements for the position prior to issuing referral lists to the selecting official. If further evaluation or interviews are required, you will be contacted. Log into your USAJOBS account to check your application status. We expect to make a final job offer approximately 40 days after the deadline for applications. This announcement may be used to fill additional like vacancies should any occur in the announced duty location(s). It is the policy of the Government not to deny employment simply because an individual has been unemployed or has had financial difficulties that have arisen through no fault of the individual. See more information at: CHCO Council. Under the Fair Chance Act, agencies are not allowed to request information about an applicant's criminal history until a conditional offer of employment has been made, except as allowed for access to classified information; assignment to national security duties or positions; acceptance or retention in the armed forces; or recruitment of a Federal law enforcement officer. An applicant may submit a complaint or any other information related to an organization's alleged noncompliance with the Fair Chance Act. The complaint must be submitted within 30 calendar days of the date of the alleged noncompliance. To make a Fair Chance Act inquiry or complaint, send an email with the appropriate information to [email protected] , subject line: Fair Chance Act.

The Federal hiring process is set up to be fair and transparent. Please read the following guidance.

  • Equal Employment Opportunity (EEO) Policy
  • Criminal history inquiries
  • Reasonable accommodation policy
  • Financial suitability
  • Selective Service
  • New employee probationary period
  • Signature and false statements
  • Privacy Act
  • Social security number request

Required Documents

How to apply, fair & transparent.

This job originated on www.usajobs.gov . For the full announcement and to apply, visit www.usajobs.gov/job/792107200 . Only resumes submitted according to the instructions on the job announcement listed at www.usajobs.gov will be considered.

Learn more about

Food Safety and Inspection Service

  • $5,000 Sign on Bonus: Newly appointed only.
  • Creditable Service for Annual Leave Accrual: Calculated to determine the annual leave accrual rate
  • Public Service Loan Forgiveness Program: For more information please visit: PSLF Program
  • $1,000 Employee Referral Bonus Award eligible : Paid to employees who refer applicants who are hired with FSIS.

Your session is about to expire!

Your USAJOBS session will expire due to inactivity in eight minutes. Any unsaved data will be lost if you allow the session to expire. Click the button below to continue your session.

Dying ex-doctor serving life for murder may soon be free after a conditional pardon and 2-year wait

ruby one line conditional assignment

Dr. Benjamin Gilmer, the longtime advocate of Virginia inmate Vince Gilmer (no relation) who is expected to be released from prison later this week, poses outside an Asheville, N.C., restaurant on April 29, 2024. (AP Photo/Sarah Rankin)[ASSOCIATED PRESS/Sarah Rankin]

RICHMOND, Va. (AP) — On paper, Vince Gilmer was granted freedom more than two years ago. Later this week, he may actually leave prison.

The former small-town North Carolina doctor and convicted murderer whose medical mystery captured widespread attention after being documented in a popular radio program and a book, was conditionally pardoned in January 2022. But because of the strict terms attached to the pardon and what his advocates describe as delay or indifference from government officials and health care institutions, he’s remained behind bars in a southwest Virginia prison as his health deteriorated.

Gilmer, 61, has Huntington’s disease, a rare, devastating and incurable disorder that attacks the brain and affects patients’ cognition and physical abilities. His diagnosis — unraveled after his conviction by the physician who took over his practice and oddly enough shares his last name — was the basis of the pardon, which was granted after many years of advocacy.

Vince Gilmer admitted to killing his father, whom he accused at trial of committing horrific acts of sexual abuse against him as a child, and he received a life sentence. Though no one claims Gilmer is innocent, his supporters argue that the outcome of his 2005 trial, where he insisted on representing himself and jurors rejected his insanity defense, would likely have been different if he had been properly diagnosed at the time. They argued that mercy, in the form of admission to a treatment center, was the more appropriate outcome.

With the help of a North Carolina lawmaker, Gilmer’s medical practice successor and now advocate and legal guardian, Dr. Benjamin Gilmer, has found a hospital willing to accept Vince Gilmer as a long-term patient, in line with the pardon terms. He received confirmation from Virginia officials that Vince Gilmer will be released Thursday, he said in an interview.

Next slide

FILE - Vince Gilmer, is shown during an interview with the Bristol Herald Courier on March 20, 2005, from the Washington County jail in Abington, Va., Gilmer, the former North Carolina doctor whose murder conviction and medical mystery captured widespread attention after being documented in a popular radio show and a book, is set to be released from the Marion prison on Thursday, May 23, 2024. (Andre Teague/Bristol Herald Courier via AP)

Photo: ASSOCIATED PRESS/Andre Teague

“It’s such a beautiful moment. But at the same time, we’re all stressed and anxious because, you know, you never know what could happen in between … the door to the prison,” Benjamin Gilmer said.

The Virginia Department of Corrections did not directly address a question about when Gilmer would be released but confirmed in a written statement that it was working through “logistics” to establish a release date “as soon as possible.”

Benjamin Gilmer, who granted a series of interviews to discuss the case, recently visited the Marion Correctional Treatment Center where Vince Gilmer is in custody, to share the news. The two men are not related.

“He had a moment of joy and expressed that as best he could. But it was a little anti-climactic in a way because he’s in such bad shape,” Benjamin Gilmer said.

Vince Gilmer is in the “terminal phases” of his illness, confined to a wheelchair and fairly close to being bedbound, struggling to eat, losing his cognitive abilities and at high risk for aspiration pneumonia, Benjamin Gilmer said.

The hospital setting will provide more robust treatment and allow Vince Gilmer to “experience a little bit of life and dignity,” including more regular visits from his mother, said Benjamin Gilmer, who has arranged secure transportation for the transfer.

“I’m praying I can get there and just hold him again,” said Vince Gilmer’s 80-year-old mother, Gloria Hitt.

Benjamin Gilmer wrote in his book, “The Other Dr. Gilmer,” that he became fascinated with Vince Gilmer’s case after he joined the family medicine clinic just outside of Asheville, where Vince Gilmer used to work. Patients and former colleagues described Vince Gilmer as a beloved community member and dedicated clinician who made house calls, remembered birthdays and cared for patients regardless of their ability to pay.

Benjamin Gilmer eventually wrote to Vince Gilmer and began the effort to try to square his reputation with the horrific crime for which he’d been convicted. His quest was documented by journalist Sarah Koenig , later the host of the wildly popular podcast “Serial,” on an episode of “This American Life” titled “Dr. Gilmer and Mr. Hyde.”

Vince Gilmer’s father, Dalton Gilmer, was found dead in southwest Virginia near the North Carolina border in 2004, shortly after Vince Gilmer checked him out of a psychiatric hospital. He had been strangled and his fingers were severed. Vince Gilmer claimed at trial that his father made a sexual advance toward him and he snapped at a time when he was also hearing voices, the Richmond Times-Dispatch previously reported , citing trial transcripts.

Two prosecutors involved in the trial could not be reached for comment. The judge who presided over it said through a spokeswoman at the firm where he now works that he is unable to comment on prior cases.

Benjamin Gilmer’s sleuthing eventually led to a Huntington’s diagnosis confirmed by lab work. He began to connect with lawyers and other advocates who would assemble a strategy to free Vince Gilmer from prison by pursuing a clemency petition.

Former Gov. Terry McAuliffe, a Democrat, denied the request. Then Gov. Ralph Northam, his Democratic successor, did too. But Northam, a physician, reconsidered and issued a conditional pardon on one of his final days in office. The terms said Vince Gilmer had to be accepted to a medical or psychiatric facility, remain on probation and parole as directed by the Virginia Parole Board and provide his own “secure” transportation.

Efforts got underway to find Vince Gilmer a placement. Benjamin Gilmer wrote that he unsuccessfully petitioned every Virginia public mental health hospital, as well as appropriate public mental health facilities in North Carolina, “but they required that Vince first be in a Virginia hospital for a state-to-state transfer. Vince was stuck in a bizarre no-man’s-land,” he wrote.

“Nobody cares that they have a man dying in their prison,” Benjamin Gilmer said in an interview before he’d received confirmation of a release date, adding that many private facilities were also reluctant to take in a convicted murderer.

Efforts by North Carolina state Sen. Julie Mayfield led to a breakthrough. Mayfield said in an interview she found a western North Carolina hospital that by mid-2023 had agreed to take Vince Gilmer.

If all goes according to plan, a welcome brigade along with a film crew working on a documentary about Vince Gilmer’s story plans to meet him Thursday in Marion, with a special meal in hand: a Coke, Twinkies and a Whopper.

Benjamin Gilmer said his advocacy for Vince Gilmer, which has now stretched over a decade, has convinced him that the United States incarcerates far too many mentally ill individuals in a way that’s “not compatible with ethics or humanity or the Hippocratic oath.”

“We haven’t had any trust in the Virginia carceral system over the years,” he said. “We’re not going to celebrate until Thursday.”

Copyright 2024 The Associated Press. All rights reserved. This material may not be published, broadcast, rewritten or redistributed without permission.

Follow us on LinkedIn

How to Use Conditional Formatting in Sage X3

Introduction

When you look at raw data, it can be hard to understand what it all means because it’s just a bunch of numbers or information. It’s difficult to see patterns or trends when the data is in this simple form.

One tool that helps with visualizing data is called conditional formatting. This tool makes it easier to see patterns and trends in your data by applying different formats to cells based on their values. For example, you can set rules so that cells with high values are highlighted in one colour while those with low values are highlighted in another colour. This way, you can quickly identify areas of interest in your data. Conditional formatting turns raw data into a visual map, making it easier to read and analyse your data.

CONDITIONAL FORMATTING IN SAGE X3

Define the criteria and the style. Enter a unique code, enter a description, and fill out the lines accordingly.

1. Fill Out the Lines Accordingly: This involves specifying how the information should be displayed based on whether the criteria are met. This could include setting the colour, text size, or other visual elements.

For example:

– Line 1: This line specifies the visual style when the price is greater than zero.

– Line 2: This line specifies the visual style when the price is less than or equal to zero.

ruby one line conditional assignment

Fig.1: Conditional Styles

  • Other Styles: In addition to the default styles that may be provided, there could be other options for you to try out. These options could include different colours, fonts, sizes, or other visual changes that alter the appearance of the information on your screen.
  • Setup > General Parameters > Presentation Styles: Another way to access and customize styles is through a setup menu in the application. You can navigate to the “Setup” section, then choose “General Parameters,” and finally go to “Presentation Styles.” Here, you may find a range of options that let you modify how information is displayed in the application.

ruby one line conditional assignment

Fig.2: Presentation Styles

Assign the style to the field. Go to Setup–>General Parameters–>Personalization–>Screen–>Conditional Style assignment.

  • Screen Personalization: Inside the Screen section, look for an option called “Conditional Style assignment” This is where you can customize the appearance of specific screens in the application.
  • Enter the Screen Code: To customize a specific screen, you’ll need to enter the code or identifier for that screen.
  • Assign the Style to the Field: Once you’ve entered the screen code, you can assign a specific style to a field on that screen. This might involve choosing a colour, font, size, or other visual elements to change how the field looks.

By assigning a style to a field, you can make that information stand out more or make it easier to read and understand.

ruby one line conditional assignment

Fig.3: Screen Personalization

In our example scenario, we’ve set up a rule where the gross price field will display in green if the price is greater than zero. Conversely, if the price is not greater than zero, the gross price field will be displayed in red. By viewing the style in action, you’ll be able to confirm whether the applied rules are working as intended.

ruby one line conditional assignment

Fig.4: Sales Order Screen

Thus, conditional formatting in Sage X3 streamlines data visualization by allowing users to define criteria and styles, assign them to fields, and observe their impact on data interpretation. This process enhances data analysis by visually highlighting patterns and trends, making it easier to identify areas of interest within the dataset .

TechRepublic

ruby one line conditional assignment

TIOBE Index for May 2024: Top 10 Most Popular Programming Languages

Fortran is in the spotlight again in part due to the increased interest in artificial intelligence.

Adobe logo on the smartphone screen is placed on the Apple macbook keyboard on red desk background.

Adobe Adds Firefly and Content Credentials to Bug Bounty Program

Security researchers can earn up to $10,000 for critical vulnerabilities in the generative AI products.

ruby one line conditional assignment

NVIDIA GTC 2024: CEO Jensen Huang’s Predictions About Prompt Engineering

"The job of the computer is to not require C++ to be useful," said Huang at NVIDIA GTC 2024.

The concept of cyber security in the White House

White House Recommends Memory-Safe Programming Languages and Security-by-Design

A new report promotes preventing cyberattacks by using memory-safe languages and the development of software safety standards.

ruby one line conditional assignment

How to Hire a Python Developer

Spend less time researching and more time recruiting the ideal Python developer. Find out how in this article.

Latest Articles

Splash graphic featuring the logo of Snowflake.

Snowflake Arctic, a New AI LLM for Enterprise Tasks, is Coming to APAC

Data cloud company Snowflake’s Arctic is promising to provide APAC businesses with a true open source large language model they can use to train their own custom enterprise LLMs and inference more economically.

Scientist, AI robot and businessman working together.

Anthropic’s Generative AI Research Reveals More About How LLMs Affect Security and Bias

Anthropic opened a window into the ‘black box’ where ‘features’ steer a large language model’s output.

Promotional graphic for the Learn to Code Certification Bundle.

Learn How to Code From Novice-Friendly Courses for Just $40 Through 5/31

Learning to code can be so easy with the classes in this bundle; most were designed for novices, and others will take you further when you’re ready.

Laptop computer displaying logo of Microsoft 365 Copilot.

Microsoft Build 2024: Copilot AI Will Gain ‘Personal Assistant’ and Custom Agent Capabilities

Other announcements included a Snapdragon Dev Kit for Windows, GitHub Copilot Extensions and the general availability of Azure AI Studio.

A developer writing code in Python.

Learn the Python Programming Language Online for Just $24

Get certified for the most popular language used by software development companies with these ten online training courses. Use code TRA20 at checkout to unlock an extra 20% off its already discounted price.

devp.jpg

The Apple Developer Program: What Professionals Need to Know

If you want to develop software for macOS, iOS, tvOS, watchOS or visionOS, read this overview of Apple's Developer Program.

Businessman uses artificial intelligence AI technology for enhanced work efficiency data analysis and efficient tools.

U.K.’s AI Safety Institute Launches Open-Source Testing Platform

Inspect is the first AI safety testing platform created by a state-backed body to be made freely available to the global AI community.

ruby one line conditional assignment

Google I/O 2024: Google Search’s AI Overviews Are Generally Available This Week

Plus, Google reveals plans to unleash Gemini across Workspace to make interpreting long email threads or creating spreadsheets easier.

Fortran programming language.

TIOBE Index News (May 2024): Why is Fortran Popular Again?

The AI boom is starting to show up on the TIOBE Index by bringing back a formative programming language.

Businessman add new skill or gear into human head to upgrade working skill.

Udemy Report: Which IT Skills Are Most in Demand in Q1 2024?

Informatica PowerCenter, Microsoft Playwright and Oracle Database SQL top Udemy’s list of most popular tech courses.

Students learning AI topics online.

The 10 Best AI Courses in 2024

Today’s options for best AI courses offer a wide variety of hands-on experience with generative AI, machine learning and AI algorithms.

ruby one line conditional assignment

Learn Windows PowerShell for just $17

Streamline your workflow, automate tasks and more with The 2024 Windows PowerShell Certification Bundle.

ruby one line conditional assignment

Llama 3 Cheat Sheet: A Complete Guide for 2024

Learn how to access Meta’s new AI model Llama 3, which sets itself apart by being open to use under a license agreement.

An illustration of a monthly salary of a happy employee on year 2024.

How Are APAC Tech Salaries Faring in 2024?

The year 2024 is bringing a return to stable tech salary growth in APAC, with AI and data jobs leading the way. This follows downward salary pressure in 2023, after steep increases in previous years.

Create a TechRepublic Account

Get the web's best business technology news, tutorials, reviews, trends, and analysis—in your inbox. Let's start with the basics.

* - indicates required fields

Sign in to TechRepublic

Lost your password? Request a new password

Reset Password

Please enter your email adress. You will receive an email message with instructions on how to reset your password.

Check your email for a password reset link. If you didn't receive an email don't forgot to check your spam folder, otherwise contact support .

Welcome. Tell us a little bit about you.

This will help us provide you with customized content.

Want to receive more TechRepublic news?

You're all set.

Thanks for signing up! Keep an eye out for a confirmation email from our team. To ensure any newsletters you subscribed to hit your inbox, make sure to add [email protected] to your contacts list.

  • Python Basics
  • Interview Questions

Python Quiz

  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • Python Turtle Tutorial
  • Python Pillow Tutorial
  • Python Tkinter Tutorial
  • Python Requests Tutorial
  • Selenium Python Tutorial
  • Pygal Tutorial
  • OpenCV Tutorial in Python
  • Python Automation Tutorial
  • Pandas Tutorial
  • PyGame Tutorial
  • Python Web Scraping Tutorial
  • NumPy Tutorial - Python Library
  • Advanced Python Topics Tutorial
  • Python Syntax
  • Flask Tutorial
  • Python - Data visualization tutorial
  • Machine Learning with Python Tutorial
  • Python Tkinter - Label
  • Python Tkinter - Message

Python Tutorial | Learn Python Programming

This Programming Language Python Tutorial is very well suited for beginners and also for experienced programmers. This specially designed free Python tutorial will help you learn Python programming most efficiently, with all topics from basics to advanced (like Web-scraping, Django, Learning, etc.) with examples.

What is Python?

Python is a high-level, general-purpose, and very popular programming language. Python programming language (latest Python 3) is being used in web development, and Machine Learning applications, along with all cutting-edge technology in Software Industry. Python language is being used by almost all tech-giant companies like – Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.

Writing your first Python Program to Learn Python Programming

There are two ways you can execute your Python program:

  • First, we write a program in a file and run it one time.
  • Second, run a code line by line.

Here we provided the latest Python 3 version compiler where you can edit and compile your written code directly with just one click of the RUN Button. So test yourself with Python first exercises.

Let us now see what will you learn in this Python Tutorial, in detail:

The first and foremost step to get started with Python tutorial is to setup Python in your system.

Python Tutorial

Below are the steps based your system requirements:

Setting up Python

  • Download and Install Python 3 Latest Version
  • How to set up Command Prompt for Python in Windows10
  • Setup Python VS Code or PyCharm
  • Creating Python Virtual Environment in Windows and Linux
Note: Python 3.13 is the latest version of Python, but Python 3.12 is the latest stable version.

Now let us deep dive into the basics and components to learn Python Programming:

Getting Started with Python Programming

Welcome to the Python tutorial section! Here, we’ll cover the essential elements you need to kickstart your journey in Python programming. From syntax and keywords to comments, variables, and indentation, we’ll explore the foundational concepts that underpin Python development.

  • Learn Python Basics
  • Keywords in Python
  • Comments in Python
  • Learn Python Variables
  • Learn Python Data Types
  • Indentation and why is it important in Python

Learn Python Input/Output

In this segment, we delve into the fundamental aspects of handling input and output operations in Python, crucial for interacting with users and processing data effectively. From mastering the versatile print() function to exploring advanced formatting techniques and efficient methods for receiving user input, this section equips you with the necessary skills to harness Python’s power in handling data streams seamlessly.

  • Python print() function
  • f-string in Python
  • Print without newline in Python
  • Python | end parameter in print()
  • Python | sep parameter in print()
  • Python | Output Formatting
  • Taking Input in Python
  • Taking Multiple Inputs from users in Python

Python Data Types

Python offers, enabling you to manipulate and manage data with precision and flexibility. Additionally, we’ll delve into the dynamic world of data conversion with casting, and then move on to explore the versatile collections Python provides, including lists, tuples, sets, dictionaries, and arrays.

Python Data Types

By the end of this section, you’ll not only grasp the essence of Python’s data types but also wield them proficiently to tackle a wide array of programming challenges with confidence.

  • Python List
  • Python Tuples
  • Python Sets
  • Python Dictionary
  • Python Arrays
  • Type Casting

Python Operators

From performing basic arithmetic operations to evaluating complex logical expressions, we’ll cover it all. We’ll delve into comparison operators for making decisions based on conditions, and then explore bitwise operators for low-level manipulation of binary data. Additionally, we’ll unravel the intricacies of assignment operators for efficient variable assignment and updating. Lastly, we’ll demystify membership and identity operators, such as in and is, enabling you to test for membership in collections and compare object identities with confidence.

  • Arithmetic operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Membership & Identity Operators | Python “in”, and “is” operator

Python Conditional Statement

These statements are pivotal in programming, enabling dynamic decision-making and code branching. In this section of Python Tutorial, we’ll explore Python’s conditional logic, from basic if…else statements to nested conditions and the concise ternary operator. We’ll also introduce the powerful match case statement, new in Python 3.10. By the end, you’ll master these constructs, empowering you to write clear, efficient code that responds intelligently to various scenarios. Let’s dive in and unlock the potential of Python’s conditional statements.

  • Python If else
  • Nested if statement
  • Python if-elif-else Ladder
  • Python If Else on One Line
  • Ternary Condition in Python
  • Match Case Statement

Python Loops

Here, we’ll explore Python’s loop constructs, including the for and while loops, along with essential loop control statements like break, continue, and pass. Additionally, we’ll uncover the concise elegance of list and dictionary comprehensions for efficient data manipulation. By mastering these loop techniques, you’ll streamline your code for improved readability and performance.

  • Loop control statements (break, continue, pass)
  • Python List Comprehension
  • Python Dictionary Comprehension

Python Functions

Functions are the backbone of organized and efficient code in Python. Here, we’ll explore their syntax, parameter handling, return values, and variable scope. From basic concepts to advanced techniques like closures and decorators. Along the way, we’ll also introduce versatile functions like range(), and powerful tools such as *args and **kwargs for flexible parameter handling. Additionally, we’ll delve into functional programming with map, filter, and lambda functions.

  • Python Function syntax
  • Arguments and Return Values in Python Function
  • Python Function Global and Local Scope Variables
  • Use of pass Statement in Function
  • Return statemen in Python Function
  • Python range() function
  • *args and **kwargs in Python Function
  • Python closures
  • Python ‘Self’ as Default Argument
  • Decorators in Python
  • Map Function
  • Filter Function
  • Reduce Function
  • Lambda Function

Python OOPs Concepts

In this segment, we’ll explore the core principles of object-oriented programming (OOP) in Python. From encapsulation to inheritance, polymorphism, abstract classes, and iterators, we’ll cover the essential concepts that empower you to build modular, reusable, and scalable code.

  • Python Classes and Objects
  • Polymorphism
  • Inheritance
  • Encapsulation

Python Exception Handling

In this section of Python Tutorial, we’ll explore how Python deals with unexpected errors, enabling you to write robust and fault-tolerant code. We’ll cover file handling, including reading from and writing to files, before diving into exception handling with try and except blocks. You’ll also learn about user-defined exceptions and Python’s built-in exception types.

  • Python File Handling
  • Python Read Files
  • Python Write/Create Files
  • Exception handling
  • User defined Exception
  • Built-in Exception
  • Try and Except in Python

Python Packages or Libraries

The biggest strength of Python is a huge collection of standard libraries which can be used for the following:

  • Built-in Modules in Python
  • Python DSA Libraries
  • Machine Learning
  • Python GUI Libraries
  • Web Scraping Pakages
  • Game Development Packages
  • Web Frameworks like, Django , Flask
  • Image processing (like OpenCV , Pillow )

Python Collections

Here, we’ll explore key data structures provided by Python’s collections module. From counting occurrences with Counters to efficient queue operations with Deque, we’ll cover it all. By mastering these collections, you’ll streamline your data management tasks in Python.

  • OrderedDict
  • Defaultdict

Python Database Handling

In this section you will learn how to access and work with MySQL and MongoDB databases

  • Python MongoDB Tutorial
  • Python MySQL Tutorial

Python vs. Other Programming Languages

Here’s a comparison of Python with the programming languages C, C++, and Java in a table format:

Let us now begin learning about various important steps required in this Python Tutorial.

Learn More About Python with Different Applications :

Python is a versatile and widely-used programming language with a vast ecosystem. Here are some areas where Python is commonly used:

  • Web Development : Python is used to build web applications using frameworks like Django, Flask, and Pyramid. These frameworks provide tools and libraries for handling web requests, managing databases, and more.
  • Data Science and Machine Learning : Python is popular in data science and machine learning due to libraries like NumPy, pandas, Matplotlib, and scikit-learn. These libraries provide tools for data manipulation, analysis, visualization, and machine learning algorithms.
  • Artificial Intelligence and Natural Language Processing : Python is widely used in AI and NLP applications. Libraries like TensorFlow, Keras, PyTorch, and NLTK provide tools for building and training neural networks, processing natural language, and more.
  • Game Development : Python can be used for game development using libraries like Pygame and Panda3D. These libraries provide tools for creating 2D and 3D games, handling graphics, and more.
  • Desktop Applications : Python can be used to build desktop applications using libraries like Tkinter, PyQt, and wxPython. These libraries provide tools for creating graphical user interfaces (GUIs), handling user input, and more.
  • Scripting and Automation : Python is commonly used for scripting and automation tasks due to its simplicity and readability. It can be used to automate repetitive tasks, manage files and directories, and more.
  • Web Scraping and Crawling : Python is widely used for web scraping and crawling using libraries like BeautifulSoup and Scrapy. These libraries provide tools for extracting data from websites, parsing HTML and XML, and more.
  • Education and Research : Python is commonly used in education and research due to its simplicity and readability. Many universities and research institutions use Python for teaching programming and conducting research in various fields.
  • Community and Ecosystem : Python has a large and active community, which contributes to its ecosystem. There are many third-party libraries and frameworks available for various purposes, making Python a versatile language for many applications.
  • Cross-Platform : Python is a cross-platform language, which means that Python code can run on different operating systems without modification. This makes it easy to develop and deploy Python applications on different platforms.

To achieve a solid understanding of Python, it’s very important to engage with Python quizzes and MCQs. These quizzes can enhance your ability to solve similar questions and improve your problem-solving skills.

Here are some quiz articles related to Python Tutorial:

  • Python MCQs
  • Python Sets Quiz
  • Python List Quiz
  • Python String Quiz
  • Python Tuple Quiz
  • Python Dictionary Quiz

Python Latest & Upcoming Features

Python recently release Python 3.12 in October 2023 and here in this section we have mentioned all the features that Python 3.12 offer. Along with this we have also mentioned the lasted trends.

  • Security Fix: A critical security patch addressing potential vulnerabilities (details not publicly disclosed).
  • SBOM (Software Bill of Materials) Documents: Availability of SBOM documents for CPython, improving transparency in the software supply chain.

Expected Upcoming Features of Python 3.13

  • Pattern Matching (PEP 635): A powerful new syntax for pattern matching, potentially similar to features found in languages like Ruby. This could significantly improve code readability and maintainability.
  • Union Typing Enhancements (PEP 647): Extending type annotations for unions, allowing for more precise type definitions and improved static type checking.
  • Improved Exception Groups (PEP 653): A new mechanism for grouping related exceptions, making error handling more organized and user-friendly.

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

Things you buy through our links may earn  Vox Media  a commission.

LaToya Ruby Frazier’s MoMA Show Does Too Much

Portrait of Madeline Leung Coleman

As long as she could remember, LaToya Ruby Frazier’s hometown had been in trouble. She was born in Braddock, Pennsylvania, in 1982, too late for the theaters, shops, and stable jobs at the steel mill that her Grandma Ruby remembered and just in time for the decline of American steel and the “war on drugs.” The Braddock that Frazier knew was exhausted, as were her great-grandfather, her grandmother, her mother. But she wasn’t exhausted yet. Not quite 20, she got her hands on a camera and started working. In clear-eyed black and white, she put her own frame around her life. At first, her photographs and videos captured what was already there: Grandma Ruby smoking Pall Malls in the living room, the broken face of the town. Then she started building what she needed to see. Raised by her grandmother, she reconciled with her mother in posed double portraits, their profiles overlapping and switching off. When she shot herself alone, her face was commanding while her eyes were soft, and she leaned toward the camera like a yearning new lover. It was her first major body of work, the one she used to teach herself to be an artist — and helped her find out that she already was one. She called the series “The Notion of Family.”

There’s a reason why sophomore slump is so common. The first big thing you put out tends to be the one you’ve been making all your life. When Frazier started showing “The Notion of Family” toward the end of the aughts, she ripped out of the gate with a series so airtight that it created its own atmosphere, one where the raw fact of Braddock’s steel mill hangs over her family, their strength, their illnesses, their fight, their comforts, their humor, their deaths. Her pictures of abandoned buildings aren’t ruin porn: They’re Braddock’s phantom limbs. An entire world can be found in one image. In her pulled-back 2010 photograph Mom and Me on the Couch, we see a 20-something Frazier and her mother sitting on opposite ends of a sofa, both wearing white tank tops and jeans, both looking down or away, hands to temples, worn out. An argument hangs in the air; Frazier’s photographs hang on her mother’s walls. (We know they’re hers because some are part of the same series.) The fact that Frazier’s first solo exhibition at MoMA, “Monuments of Solidarity,” starts its two-decade-plus survey of her work with “The Notion of Family” makes sense. It also sets the level for a show which — if you can make it all the way through — you’ll leave feeling both elated by the clarity of the images and totally pummeled by the avalanche of text that accompanies them. If only the rest of the show trusted photography as much as “The Notion of Family” does.

Frazier has said that when she started photographing seriously in college, she was both inspired and infuriated by the work of Farm Security Administration photographers like Dorothea Lange: As she saw it, they were deployed by the government to make images of the bottom that could support the policies that came from the top. She wanted to get out from under — to make pictures that Florence Owens Thompson, the woman in Migrant Mother, might’ve made if she’d been given the camera instead. Frazier never stopped looking at workers: Organized labor and its ghosts are all over this show, which includes series made everywhere from Flint, Michigan, to a GM plant in Lordstown, Ohio. But when she wrapped “The Notion of Family” and started photographing people who weren’t related to her, she had to redefine the notion of agency. Now Frazier is the Lange in the scenario, the successful artist telling other people’s stories with her camera.

At MoMA we see her wrestle with this change. In a couple cases, she does find ways to turn her subjects into true collaborators, nesting their point of view in hers. In others, she tries to bridge the gap by pairing her portraits with long — very long — transcripts of their words. The show is full of these text panels, set up on placards next to Frazier’s photographs in the middle of the galleries: lopsided duets that, if you were obedient, would take hours to read.

Do you have the bandwidth for that? Does a family of dehydrated MoMA-attending tourists? “Monuments of Solidarity” is a show that makes you think hard about venue and scope, and how (or whether) an artist of Frazier’s commitment and range is really best served by a sprawling survey that by its nature privileges breadth over depth. Frazier is so good at working deep that doing both here feels like trying to swim Lake Superior. If you leave the galleries thinking This should’ve been a book , you and those tourists are in luck: The book is for sale in the shop downstairs.

Frazier made more work in her hometown as she was wrapping up “The Notion of Family,” including a kind of zine that both protests the closure of the town’s only hospital and critiques a Levi’s campaign shot in Braddock around the same time. (The brand was invited in by then-Mayor John Fetterman, who was happy for Braddock to be painted as a postindustrial, denim-clad frontier town.) But the next-strongest series here is another that Frazier worked on for years, “Flint Is Family in Three Acts.” It started in 2016 when Frazier took an editorial assignment from Elle magazine to photograph women living through Flint’s horrifying, government-inflicted water crisis. She turned this brief contact into a long-term alliance with two of the locals she focused on, Shea Cobb and Amber Hasan.

ruby one line conditional assignment

The first act is presented here as a film projected on the wall in which Cobb reads her own poem over a sequence of Frazier’s photographs. The second act is what Frazier has called “the real story”: when Cobb accepted her father’s invitation to take her daughter, Zion, and move down to the family land in Mississippi. (He convinced her by sending her a snapshot of her own young self drinking from a freshwater spring there with the words, “This water won’t kill you. Come home.”) Frazier followed, and the images she made of the family on their land are stirring and sublime. In one photograph presented here as a luscious four-foot-by-five-foot gelatin-silver print, we see Cobb; Zion; and Cobb’s father, Mr. Smiley, from the back, leading us deeper onto their property. Ahead of them, we see a grazing horse and a barn, its sides wide open and generous. Above them an ancient tree stretches its branches, protective. The third act was direct action, documented. Frazier used the money she made selling prints at the influential gallery Gavin Brown’s Enterprise (plus matching funds from the Rauschenberg Foundation) to acquire an atmospheric water generator, a machine that turns moisture from the air into drinkable water, which she, Hasan, and Cobb transported to and installed in Flint.

This is just one of the many times in the show you might start thinking about the price of things. To be a successful working artist in the U.S. means selling both your story and your work to a class of people who have never in their life worried that their city would care so little about them that it would poison them and deny it. These are people who have likely never made contact with a community health worker — some of whom Frazier photographed in Baltimore in 2021 and 2022 — whose role is to connect locals with the medical services they desperately need. Nor have they endured the arbitrary shuttering of their workplace, as the subjects in Frazier’s project “The Last Cruze” did when their GM plant in Ohio was closed in 2019. Sadly, this particular project, which includes portraits of UAW workers and accompanying panels of their words, is presented in a way that sets it up to fail. This work is mounted on a series of red panels meant to evoke an auto assembly line, stretching down the center of a long hall. They are installed so close together, like library stacks, that you have to shuffle through them sideways to see the work.

Perhaps knowing whom she needs to convince, Frazier endeavors to make her subjects heroic. An intriguing corner of the show is the one dedicated to former Pittsburgh steelworker and self-taught photographer Sandra Gould Ford, who broke her plant’s rules to save documents and make haunting photographs of the inside of the mill. Prints of Ford’s photographs are hung alongside cyanotype prints Frazier made of the documents as well as monumental portraits Frazier took of Ford in 2017, clutching her hard hat and wearing a half-smile. Annoyingly, this is all presented in a neon-lit niche, where the overhead lights waver from bright white to blue to red. This means that a corner dedicated to exposing work conditions is hard to actually see. The weakest part of the exhibition is the most obviously iconic: a small room at the end dedicated to Frazier’s recent photographs of Delano, California, and the legendary labor organizer Dolores Huerta, who co-founded what would become the United Farm Workers with Cesar Chavez. Huerta is beyond worthy of recognition, but this section felt rushed and half-baked, the photographs of Huerta stiff and posed.

The title of the show, “Monuments of Solidarity,” is meant to ennoble Frazier’s subjects and collaborators. But the word monument implies a rigidity, a distance from the mess of life, that you don’t really feel in these images. Frazier has said that she wants to “stand in the gap between working-class and creative-class people,” which reminds me — a creative-class person — of the first time I encountered her photographs. It was around a decade ago, on a printed-out book proof that I was marking up with a pen: I was in my early 20s and working as a copy editor at the photo publisher Aperture, where we were preparing to put out the monograph for “The Notion of Family.” My bosses were very excited that we were doing the book. I understood that Frazier was a rising star. I was also barely making any money. So although I admired the book — was unnerved by it — when I got my staff copy (retail price $60) I kept it in the plastic, thinking its value would increase and I could sell it if I was ever short on cash.

Before going to MoMA last week, I took that copy out of the plastic in a gesture of financial stability. (I checked the price for this first edition online; one copy was going for $375.) I was knocked sideways by the tenderness of the images, by their toughness — by Frazier’s obvious feel for what she wanted to show us and how. After I walked through the show, I couldn’t stop thinking about what a strange fit her labor-celebrating, inequality-exposing vision was for MoMA, perhaps the New York museum that feels most like a department store. You might agree even if you don’t know, for example, that MoMA’s current job listing for a full-time security officer offers an hourly wage of $23.80 — which nets out to less than $50,000 a year in one of the most expensive cities in the country. You don’t need to think about the workers standing in the gallery with you to feel tension from seeing these pictures, in this place. But what would happen if you did?

Correction: A previous version of this story misstated who designed the layout for “The Last Cruze.”

  • vulture section lede
  • vulture homepage lede
  • photography
  • new york magazine

Most Viewed Stories

  • Fire Jeff Probst
  • Cinematrix No. 65: May 24, 2024
  • Ella Purnell Is Hollywood’s New Favorite Action Hero
  • 21 Ways to Hack Stardom
  • The Double Loss of Under the Bridge
  • Vanderpump Rules Should Have Done This Years Ago

Editor’s Picks

ruby one line conditional assignment

Most Popular

What is your email.

This email will be used to sign into all New York sites. By submitting your email, you agree to our Terms and Privacy Policy and to receive email correspondence from us.

Sign In To Continue Reading

Create your free account.

Password must be at least 8 characters and contain:

  • Lower case letters (a-z)
  • Upper case letters (A-Z)
  • Numbers (0-9)
  • Special Characters (!@#$%^&*)

As part of your account, you’ll receive occasional updates and offers from New York , which you can opt out of anytime.

IMAGES

  1. [Ruby]Write a conditional expression with an if

    ruby one line conditional assignment

  2. Conditional Assignment in Ruby

    ruby one line conditional assignment

  3. Conditional Statements in Ruby

    ruby one line conditional assignment

  4. Ruby Programming

    ruby one line conditional assignment

  5. Different types of "Conditional Statements" in Ruby

    ruby one line conditional assignment

  6. Simple game creation using Ruby conditional branching

    ruby one line conditional assignment

VIDEO

  1. THERE'S ALWAYS SOMETHING TO LEARN AND IMPROVE ON!!💖BEST RUBY BUILD AND ROTATION 2024

  2. A NEW SEASON TO USE RUBY AND DOMINATE THE META!!🔥BEST RUBY BUILD AND ROTATION 2024

  3. RUBY CORE ITEMS YOU SHOULD ALWAYS RUSH!!🔥RUBY BEST BUILD 2023

  4. 2 ANTI HEALS AGAINST DAMAGE RUBY??!?!🤣BEST RUBY BUILD AND ROTATION 2024

  5. Ruby understands the assignment (Bfdia 7 re- animated)

  6. AM I THE SUPPORT?!?!👁️👄👁️BEST RUBY BUILD AND ROTATION 2024

COMMENTS

  1. syntax

    23. The two one liners that exist are the two you already described: Ternary: if-struct: So to answer your questions: The ternary is preferred according to this, this , while the if-struct is preferred according to this, and this. Ruby does not have an official style guide, you won't find a concrete answer I'm afraid.

  2. Conditional assignment

    Conditional assignment. Ruby is heavily influenced by lisp. One piece of obvious inspiration in its design is that conditional operators return values. This makes assignment based on conditions quite clean and simple to read. There are quite a number of conditional operators you can use. Optimize for readability, maintainability, and concision.

  3. How to Use The Ruby Ternary Operator (?:)

    That's part of the syntax! It's how Ruby knows that you're writing a ternary operator. Next: We have whatever code you want to run if the condition turns out to be true, the first possible outcome. Then a colon (: ), another syntax element. Lastly, we have the code you want to run if the condition is false, the second possible outcome.

  4. The Beginners Guide to Ruby If & Else Statements

    Notice that we use two equal == symbols to mean equality!. One equals sign = in Ruby means "assignment", make sure to use == when you want to find out if two things are the same.. If you don't this right you won't get the expected results. Ruby Unless Statement. With an if statement you can check if something is true.. But when you want to check for the opposite "not true" (false ...

  5. Conditional Logic

    Ruby Course. Introduction. This lesson is all about controlling the flow of your code. When you have some code that you only want to execute under specific conditions, you will need a way for the computer to check whether those conditions have been met. Conditional logic can be found everywhere in everyday life.

  6. Ruby Gotcha: single line conditionals

    In Ruby, we can write a conditional containing a single expression that normally takes up three lines: unless condition something end. on a single line to save space: something unless condition. And that is all well and good - these two are pretty much the same. But they're not identical in practice. There are a few weird things about to come up.

  7. Conditional Statements in Ruby

    If Statements. The most basic form of a conditional statement is the if statement. It allows us to execute a block of code only if a certain condition is met. Here is a simple example: age = 25. if age > 18. puts "You are an adult!" end. In this example, we first declare a variable age with a value of 25.

  8. control_expressions

    When ruby parses this expression it first encounters a as a method call in the "then" expression, then later it sees the assignment to a in the "test" expression and marks a as a local variable. When running this line it first executes the "test" expression, a = 0.zero?. Since the test is true it executes the "then" expression, p a.

  9. Ruby

    If - Elseif - Else Statements. If the if statement is not true, the block of code in the elseif statement will be executed if the condition is true. There may me multiple elseif statements. Finally, if none of the conditions are true, the block of code in the else statement will be executed.

  10. Shorthand Ruby Operators for Assignment Conditionals

    Assignment from Conditionals. Another handy assignment feature: "x" elsif y. "y" elsif z. "z" end. result = "x" elsif y. result = "y" elsif z. result = "z" else result = nil end. You can also put the if on the same line as result = , but then you should probably indent everything underneath to line up (see: Indent Conditional Assignment ...

  11. Understanding the Conditions in Ruby on Rails: A Guide with Code

    2. Conditional Expressions in Rails: Apart from the conditional statements, Rails provides additional methods and expressions that allow you to work with conditions more conveniently. 2.1. Ternary Operator: The ternary operator is a concise way to express conditional statements. It allows you to assign a value to a variable based on a condition.

  12. Learn Ruby: Refactoring Cheatsheet

    In Ruby, the return keyword in a method can be omitted making it an implicit return, in which Ruby automatically returns the result of the last evaluated expression. def product(x,y) x * y. end. product(5, 4) # => 20. #In this example, Ruby evaluates the product method and returns 20 even though the return keyword was omitted.

  13. Ruby Assignments in Conditional Expressions :: Julien Chien

    SyntaxError: invalid syntax. Most likely, the assignment in a conditional expression is a typo where the programmer meant to do a comparison == instead. This kind of typo is a big enough issue that there is a programming style called Yoda Conditionals , where the constant portion of a comparison is put on the left side of the operator.

  14. One-liner introduction

    Filtering. Ruby one-liners can be used for filtering lines matched by a regular expression (regexp), similar to the grep, sed and awk commands. And similar to many command line utilities, Ruby can accept input from both stdin and file arguments. # sample stdin data. $ printf 'gate\napple\nwhat\nkite\n'.

  15. assignment

    Assignment. In Ruby, assignment uses the = (equals sign) character. This example assigns the number five to the local variable v: v = 5. Assignment creates a local variable if the variable was not previously referenced. An assignment expression result is always the assigned value, including assignment methods.

  16. Ruby Style Guide

    Introduction. Role models are important. This Ruby style guide recommends best practices so that real-world Ruby programmers can write code that can be maintained by other real-world Ruby programmers. A style guide that reflects real-world usage gets used, while a style guide that holds to an ideal that has been rejected by the people it is ...

  17. assignment

    Assignment ¶ ↑. In Ruby assignment uses the = (equals sign) character. This example assigns the number five to the local variable v: v = 5. Assignment creates a local variable if the variable was not previously referenced. Local Variable Names ¶ ↑. A local variable name must start with a lowercase US-ASCII letter or a character with the ...

  18. USAJOBS

    A pre-assignment medical examination must be taken and passed prior to appointment to this position. ... Notification of Personnel Action that shows: (1) permanent or career-conditional tenure (codes 1 or 2, in block 24), and ... Please ensure you have completed the application process by verifying the status of your application on-line to ...

  19. USAJOBS

    $5,000 Sign on Bonus, Creditable Service for Annual Leave Accrual, Public Service Loan Forgiveness, and Referral Bonus Awards are available. Click Learn more about this agency below.<br> <br> Shifts and species will vary based on assignment. For additional information contact the Alameda District -Sandy Cai @ [email protected] or Tutu Sidhu @ sukhdeep.sidhu@usda ...

  20. Dying ex-doctor serving life for murder may soon be free after a

    RICHMOND, Va. (AP) — On paper, Vince Gilmer was granted freedom more than two years ago. Later this week, he may actually leave prison.

  21. How to Use Conditional Formatting in Sage X3

    CONDITIONAL FORMATTING IN SAGE X3. Step 1. Define the criteria and the style. Enter a unique code, enter a description, and fill out the lines accordingly. 1. Fill Out the Lines Accordingly: This involves specifying how the information should be displayed based on whether the criteria are met. This could include setting the colour, text size ...

  22. Introduction to Ruby: Origins, Types, and Operations

    Web Technology 6 - 4 Ruby and Rails TECHNICAL PUBLICATIONS ® - an up-thrust for knowledge 6.2.2 Variable and Assignment Statements The variable used for storing the data values. The variables in Ruby are case sensitive. It may contain the letters, underscore and digits. Conventionally the variable must be declared in the lower case. Ruby Script [VariableDemo.rb] pi =3.14 r=15 puts "The value ...

  23. BUS5003 Module 5 Assignment.pdf

    View BUS5003 Module 5 Assignment.pdf from BUS 5003 at Nexford University. 1. Introduction: In 2019, I faced a significant decision regarding my business and career. ... In line with (Stobierski, 2019), ... 2 What is the authors opinion about the use of the 1st conditional 3 What does. document. SHARING OF LOCATION Using Google Maps you can ...

  24. Ruby variable assignment in a conditional "if" modifier

    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 ...

  25. Developer

    Developer TR Academy Learn the Python Programming Language Online for Just $24 . Get certified for the most popular language used by software development companies with these ten online training ...

  26. Python Tutorial

    First, we write a program in a file and run it one time. Second, run a code line by line. Here we provided the latest Python 3 version compiler where you can edit and compile your written code directly with just one click of the RUN Button. So test yourself with Python first exercises. Python3.

  27. Is assignment in a conditional clause good ruby style?

    The reason it's bad is because it's usually the case that you are doing a straight up equality check in a conditional (with == ), and assignment ( =) is a common typo. Requiring surrounding parentheses when you do assignment in conditional is an extra hint to the reader that the assignment was INTENTIONAL, not a typo. - Devon Parsons.

  28. LaToya Ruby Frazier MoMA Review: Not Served by Its Venue

    In her pulled-back 2010 photograph Mom and Me on the Couch, we see a 20-something Frazier and her mother sitting on opposite ends of a sofa, both wearing white tank tops and jeans, both looking ...