Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- =begin #signature
- Developer : Ruben Verstraten
- File : fav_foods.rb
- Project : CareerFoundry Exercise 3.3: Data Structures
- Date : 2018-05-19
- Description : Exercise for learning:
- : - array methods
- : - each loops
- =end #signature
- # A little extra exploration into Ruby variables and their scope:
- # $food_array = [] # Global variable (scope inside method as well)
- # @food_array = [] # Instance variable (scope inside method as well)
- # food_array = [] # Local variable (no scope in method: needs return)
- # food_array = Array.new # Another way to declare an empty local array
- # Simple method that gets 3 favorite foods from the user
- def fav_foods
- food_array_i = []
- puts ""
- 3.times do
- puts "Name a favorite food:"
- food_array_i << gets.chomp
- end
- return food_array_i
- end
- # Declare food_array, and call fav_foods, which gives it values
- food_array = fav_foods
- # Output the list of favorite foods
- # The elements are joined into 1 string (seperated with ", ")
- puts "\nYour favorite foods: #{food_array.join(", ")}\n\n"
- # Output each element in a string
- # These elements are referred to as food
- food_array.each do |food|
- puts "I like #{food} too!"
- end
- puts "\n"
- # Alternative way of doing the same each-loop:
- food_array.each { |food| puts "I like #{food} too!"}
- puts "\n"
Add Comment
Please, Sign In to add comment