- About Ruby
- Ruby Basics
- String, Printing and Symbols
- Ruby Arrays And Hashes
- Control Structures
- Functions
- Classes
- Modules
- And More
Example code based on
LearnXinYminutes
and licensed under
CC Attribution-Share 3
Control Structures
Conditional Statements
#if statement
if true
"if statement"
elsif false
"else if, optional"
else
"else, also optional"
end
#case/switch statement
grade = 'B'
case grade
when 'A'
puts "Hooray!"
when 'B'
puts "OK job"
when 'C'
puts "You can do better"
when 'F'
puts "You failed!"
else
puts "Alternative grading system, eh?"
end
#=> OK job
#case with ranges
grade = 72
case grade
when 90..100
puts "Hooray!"
when 80...90
puts "OK job"
when 70...80
puts "You can do better"
else
puts "You failed!"
end
#=> You can do better
Ruby Loops
# A for loop in Ruby uses a Range:
for counter in 1..5
puts "iteration #{counter}"
end
#=> iteration 1
#=> iteration 2
#=> iteration 3
#=> iteration 4
#=> iteration 5
#while loop
counter = 1
while counter <= 5 do
puts "iteration #{counter}"
counter += 1
end
#=> iteration 1
#=> iteration 2
#=> iteration 3
#=> iteration 4
#=> iteration 5
Each and Blocks
Instead of For Loops, rubyists usually use the "each" method and pass it a block. A block is a bunch of code that you can pass to a method like "each". The "each" method of a range runs the block once for each element of the range. The block below is passed a counter as a parameter.
(1..5).each do |counter|
puts "iteration #{counter}"
end
#=> iteration 1
#=> iteration 2
#=> iteration 3
#=> iteration 4
#=> iteration 5
# You can also surround blocks in curly brackets:
(1..5).each {|counter| puts "iteration #{counter}"}
# The contents of data structures can also be iterated using each.
array.each do |element|
puts "#{element} is part of the array"
end
hash.each do |key, value|
puts "#{key} is #{value}"
end
Challenge
What will the above case statement output when given a grade
of 110?
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
You will be given an array of numbers ar
. Print each number in the array in the order it appears, unless the number is a multiple of 3. If a number is a multiple of 3, print no3
instead.
(Make sure to print everything in a given array on the same line.)
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
George Burdell
Mar 2, 2:49 PMFor this particular challenge, there is some bug on your code?
Input: 1 2 3 4 5 6
Output: 1 2 no3 4 5 no3
My Output: 1 2 no3 4 5 no3 100 no3 98 97 no3 -1 -2 no3 -2 -4 no3 -8 no3 2 4 no3 8 no3 no3 no3 no
of course this doesn't make sense given the input. Atleast to me it doesn't
Learneroo
Mar 2, 3:04 PM@George, you needed to print each case on its own line, but you were printing the output for all the cases on one line. I realized that could be confusing, so I modified it to automatically add a new line after each case. Please try submitting it again!