Beginner: if statement in one line?

Hi,

a simple question, however I did not find an answer for this:

How can I put a statement like

if 5 == 5
   puts '5'
end

in one line?

Just writing them all statements together in one line didn’t work,
and a syntax like if 5 == 5 {puts '5'} end didn’t either.

Thanks for your help.

CHeers, CHris

if 5 == 5 then puts '5' end
2 Likes
puts '5' if 5==5

you could also write something of the form:

puts '5' unless 5!=5

./Carl

Chris C. wrote:

Hi,

a simple question, however I did not find an answer for this:

How can I put a statement like

if 5 == 5
   puts '5'
end

in one line?

Just writing them all statements together in one line didn’t work,
and a syntax like if 5 == 5 {puts ‘5’} end didn’t either.

Thanks for your help.

CHeers, CHris

2 Likes

Chris C. schrieb:

How can I put a statement like

if 5 == 5
   puts '5'
end

in one line?

puts '5' if 5 == 5

:wink:

Greetings

1 Like

for if / else oneliners you can use also

( [condition] ? [true] : [false] )

es: puts ( 5 == 5 ? “equal!” : “not equal!” )

Chris C. wrote:

in one line?
puts ‘5’ if 5 == 5

Just writing them all statements together in one line didn’t work,
and a syntax like if 5 == 5 {puts ‘5’} end didn’t either.

Thanks for your help.

CHeers, CHris


M. Edward (Ed) Borasky
http://ruby-perspectives.blogspot.com/

“A mathematician is a machine for turning coffee into theorems.” –
Alfréd Rényi via Paul Erdős

1 Like

Chris C. wrote:

in one line?

Just writing them all statements together in one line didn’t work,
and a syntax like if 5 == 5 {puts ‘5’} end didn’t either.

AFAIK, you can’t use {} brackets to mark block for “if” statement, so
anything with them won’t work.

“If” uses “then” to mark beginning of its block and ends it with usual
“end”.

if 5 == 5 then
puts ‘5’
end

But you can omit “then” if you have multiple lines:

if 5 == 5
puts ‘5’
end

but for one-liners it is a must. So what you need is either:

if 5 == 5 then puts ‘5’ end

or even shorter switching “then” for “:”

if 5 == 5 : puts ‘5’ end

Chris C. [email protected] wrote:

a simple question, however I did not find an answer for this:

How can I put a statement like

if 5 == 5
puts ‘5’
end

in one line?

Sure, and make it a little more readable too:

puts ‘5’ if 5 == 5 # The condition can be at the end of the line. :slight_smile:

In addition to others answers you’ve received, keep in mind that you can
always disambigue when multiple lines go on a single line through the
use of semicolons:

if 5 == 5; puts 5; end

It happens that in this simple case, that isn’t necessary, since Ruby
lets you disambiguate with “then”:

if 5 == 5 then puts 5 end

Or, as has been pointed out, you can use the end-of-line “if” operator:

puts 5 if 5 == 5

m.

Hi,

At Sat, 12 Jul 2008 01:30:57 +0900,
Trys wrote in [ruby-talk:307868]:

or even shorter switching “then” for “:”

if 5 == 5 : puts ‘5’ end

That usage of “:” had never been an official feature, and no
longer possible. Do not use it.

And another one:

5 == 5 and puts ‘5’

Chris C. wrote:

and a syntax like if 5 == 5 {puts ‘5’} end didn’t either.

Be aware that { } blocks in Ruby don’t have the same meaning as { }
blocks in C-like languages. They’re not used for grouping statements;
rather, they’re used as code blocks (cf. anonymous subroutines, closures
etc).

Also, { } is an empty hash, which can sometimes be confusing.

x = lambda { } # an empty code block
x = { } # an empty hash

Dave

Like with shellscript, you can use && for ‘then’ and || for ‘else’ :

v=5
( v==5 )  && ( puts "5 is the value" ; puts "that's it." )
( v==6 )  ||    ( puts "6 is note the value" ; puts "that's it." )

1 Like

10 == 10 and puts ‘10’
end
I am showing you that this statement is completed in one line.I have solved this query so you can better understant here. you also read my best digital marketing training institute in rohini blogs here important information for you.

1 Like

Ruby is a kind of language that has many alternatives to do a job. You could write an if condition or an if else or even an if elsif else condition.
I am sorry this answer will be a bit long.

I assume you want to check if 5 == 5 or if true, then do something

1. Statement Modifiers:

puts ?5 if 5 == 5

2. Ternary Operators:

puts 5 == 5 ? ?5 : ''

3. If then end block in a line:

if 5 == 5 then puts ?5 end

4. Using Short Circuit Evaluators:

Short circuit evaluators are and and the && operators. Yes, they are not actually methods on an object.

5 == 5 and puts ?5    # => nil

or

5 == 5 && puts(?5)    # => nil

Here’s more about short-circuit evaluation:

5. Using the & method (Eager Operator)

The & method is available on instances of TrueClass, FalseClass and NilClass. This is not equivalent to && and and and or and ||.

5.==(5).&(puts ?5)    # => false

Bonus Stuff. Let’s build one fizzbuzz game in one line.

In fizzbuzz game, you have to iterate over a range of numbers. When a number is divisible by 3, print ‘fizz’; when a number is divisible by 5 print ‘buzz’; when a number is divisible by both 3 and 5 (or 3 * 5) then print ‘fizzbuzz’. print the number if they don’t satisfy the above conditions…

Answer:

Using if:
#!/usr/bin/ruby -w
(1..100).each do |x|
	if x.%(15).zero? then puts 'FizzBuzz'
	elsif x.%(5).zero? then puts 'Buzz'
	elsif x.%(3).zero? then puts 'Fizz'
	else puts x
	end
end
Using ternary operators:
#!/usr/bin/ruby -w

puts (1..100).map { |x| x.%(15).zero? ? 'FizzBuzz' : x.%(5).zero? ? 'Buzz' : x.%(3).zero? ? 'Fizz' : x }
You can use while, and until loops in a line too (without do end block):
#!/usr/bin/ruby -w
0.tap { |i| puts i.%(15).zero? ? 'FizzBuzz' : i.%(5).zero? ? 'Buzz' : i.%(3).zero? ? 'Fizz' : i while  (i += 1) < 100 }

Or even:

#!/usr/bin/ruby -w
puts (1..100).reduce([]) { |a, i| a.push i % 15 == 0 ? 'FizzBuzz' : i % 5 == 0 ? 'Buzz' : i % 3 == 0 ? 'Fizz' : i  }

I admit this can be written in 10 different ways again. But let’s stick with this for now!
If you are a beginner, try avoid printing (using puts, printf, p, pp, Kernel#display etc.) something in a loop, it takes a lot of time if you have to iterate over a million times. So append items to values, say, use map instead of times can be very efficient!


Sorry, this answer is a bit long, but hope this helps.

You can do one line if statements without needing a end.
Example

def $usr_io::nil
end

$usr_io = gets.chomp

do_this_thing if $usr_io =~ /a|b/
exit(0) if $usr_io =~ /banana|goober/

1 Like

(puts ‘5’) if 5==5 seems to do the job, but I dunno why normal brackets work and braces dont

5 == 5 ? puts('5') : nil

This code works like this:

  • 5 == 5 is the condition being evaluated.
  • ? separates the condition from the expression to execute if true.
  • puts('5') is the code that runs if the condition is true (5 equals 5).
  • : separates the true expression from the expression to execute if false.
  • nil is used here because there’s no specific action to take if the condition is false (5 doesn’t equal 5).
    I believe you understand, if you get in touch with me on my Red Apple Learning Kolkata full stack development course

Use 5=5
I hope this will works.