Conditionals
Goals
-
Use
getsto get input from the user of your program. - Use a conditional statement to execute a branch of code only some of the time.
Step 1
Type this in the file conditionals_test.rb:print "How many apples do you have? > " apple_count = gets.to_i puts "You have #{apple_count} apples."Type this in the terminal:ruby conditionals_test.rb
Step 2
Type this in the file conditionals_test.rb:if apple_count > 5 puts "Lots of apples!" else puts 'Not many apples...' endType this in the terminal:ruby conditionals_test.rb
Step 3
Type this in irb:15 < 5 10 == 12 'foo' != 'bar'Type this in irb:'sandwich'.end_with?('h') 'sandwich'.end_with?('z') [1,2,3].include?(2) [1,2,3].include?(9)
Step 4
Type this in the file conditional_loops.rb:fruits = ['apple', 'pear', 'apricot'] fruits.each do |fruit| if fruit.start_with?('a') puts "#{fruit} begins with the letter a." end endType this in the terminal:ruby conditional_loops.rb
Step 5
Type this in the file while_loop.rb:total = 0 user_input = nil while user_input != 'stop' print 'Enter a number to add to the total. > ' user_input = gets.chomp total = total + user_input.to_i end puts "Your final total was #{total}!"Type this in the terminal:ruby while_loop.rb
Explanation
Next Step:
Go on to Functions