Guest User

Untitled

a guest
May 24th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. =begin #signature
  2.  
  3. Developer : Ruben Verstraten
  4. File : fav_foods.rb
  5. Project : CareerFoundry Exercise 3.3: Data Structures
  6. Date : 2018-05-19
  7. Description : Exercise for learning:
  8. : - array methods
  9. : - each loops
  10.  
  11. =end #signature
  12.  
  13. # A little extra exploration into Ruby variables and their scope:
  14. # $food_array = [] # Global variable (scope inside method as well)
  15. # @food_array = [] # Instance variable (scope inside method as well)
  16. # food_array = [] # Local variable (no scope in method: needs return)
  17. # food_array = Array.new # Another way to declare an empty local array
  18.  
  19. # Simple method that gets 3 favorite foods from the user
  20. def fav_foods
  21. food_array_i = []
  22. puts ""
  23. 3.times do
  24. puts "Name a favorite food:"
  25. food_array_i << gets.chomp
  26. end
  27. return food_array_i
  28. end
  29.  
  30. # Declare food_array, and call fav_foods, which gives it values
  31. food_array = fav_foods
  32.  
  33. # Output the list of favorite foods
  34. # The elements are joined into 1 string (seperated with ", ")
  35. puts "\nYour favorite foods: #{food_array.join(", ")}\n\n"
  36.  
  37. # Output each element in a string
  38. # These elements are referred to as food
  39. food_array.each do |food|
  40. puts "I like #{food} too!"
  41. end
  42.  
  43. puts "\n"
  44.  
  45. # Alternative way of doing the same each-loop:
  46. food_array.each { |food| puts "I like #{food} too!"}
  47.  
  48. puts "\n"
Add Comment
Please, Sign In to add comment