if example in ruby

In Ruby, the "if" statement is used to execute a block of code only if a certain condition is true. The syntax for the "if" statement looks like this:

main.rb
if condition
  # code to be executed if condition is true
end
62 chars
4 lines

Here's an example:

main.rb
age = 18

if age >= 18
  puts "You are legally an adult."
end

# Output: "You are legally an adult."
101 chars
8 lines

In this example, the "if" statement checks whether the age variable is greater than or equal to 18. If it is, the code inside the "if" block is executed, which prints "You are legally an adult." to the console.

You can also use an "else" block to provide code to execute if the condition is false:

main.rb
age = 16

if age >= 18
  puts "You are legally an adult."
else
  puts "You are still a minor."
end

# Output: "You are still a minor."
135 chars
10 lines

This example checks whether the age variable is greater than or equal to 18. If it is, the code inside the "if" block is executed. Otherwise, the code inside the "else" block is executed, which prints "You are still a minor." to the console.

gistlibby LogSnag