Advertisement
Guest User

Untitled

a guest
Jun 25th, 2015
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.10 KB | None | 0 0
  1. ------------------GENERAL
  2.  
  3. - a loop iterates over a collection, i.e.,
  4. it's a programming construct that's used to step through a collection of objects
  5.  
  6. - since an Array is a collection of objects, loops can be used to iterate over arrays.
  7. - while iterating over a collection of objects, a loop can be programmed to
  8. do things to or with each object in the collection.
  9.  
  10. ------------------EACH
  11.  
  12. - .each is the most common way to program loop constructs
  13. - the .each method is called on a collection, like an Array, e.g.,
  14.  
  15. a = [2,4,6,8]
  16. a.each do |num|
  17. # pass a block of code to .each (do...end)
  18. p "We're on number: #{num}"
  19. end
  20.  
  21. - inside of the loop, you are instructing the computer to print
  22. an interpolated string with the num argument, and the num variable
  23. represents an element from the a array
  24. - with each iteration, num is assigned to a new element, i.e.,
  25. 2, 4, 6, and 8 in succession (in the given example)
  26.  
  27. ------------------EACH IN RAILS
  28.  
  29. - .each is frequently used in Rails to iterate through "model" objects
  30. (instances of classes representing data) and display their attributes on a page
  31. - we haven't yet encountered model objects and we don't yet have a web page,
  32. but we can explore usage like this in the example below (which shows how
  33. we might loop through User objects to display their info using .each):
  34.  
  35. class User
  36. attr accessor :name
  37. def initialize(name)
  38. @name = name
  39. end
  40. def email
  41. # this is an instance method? therefore: do not pass any arguments to it?
  42. "#{name.split(' ').join('')}@email.com"
  43. end
  44. end
  45.  
  46. users = [User.new("ANDREA KAO"), User.new("HERMIONE LAFORGE"), User.new("HYACINTH LAFLEUR")]
  47. users.each do |user|
  48. p "THIS USER'S NAME IS #{user.name} AND HER EMAIL IS #{user.email}."
  49. end
  50.  
  51. - this loops through the users collection and outputs a string for each one
  52. - because .each is a method, it returns something at the end of the loop:
  53. the same collection of users on which it was originally called
  54.  
  55. - **** .each performs operations on a collection, but returns the original
  56. collection, rather than anything related to what is performed within the
  57. do...end block. In this sense, we'd say that .each is used for its "side
  58. effects" (i.e., the printed string) rather than its "return".
  59.  
  60. ------------------MIXING CLASSES AND LOOPS
  61.  
  62. - this new class takes an array of user info on initialization
  63. - its print_names_and_emails method loops through the users and
  64. prints a string for each one, e.g.,
  65.  
  66. # User class defined above
  67. class UserIterator
  68.  
  69. attr_accessor :user_array
  70. def initialize(user_array)
  71. @user_array = user_array
  72. end
  73.  
  74. def print_names_and_emails
  75. user_array.each do |user|
  76. p "This user's name is #{user.name} and their email is #{user.email}
  77. end
  78. end
  79. end
  80.  
  81. users = [User.new("ANGELA LANSBURY"), User.new("CLORIS LEACHMAN"), User.new("HELEN MIRREN")]
  82. # declare the array and its values
  83.  
  84. UserIterator.new(users).print_names_and_emails
  85. # chain together 2 methods: .new & .print_names_and_emails
  86. # this will also return the original array of users (thanks to the .each method)
  87.  
  88. - this UserIterator class example behaves identically to the User class example above
  89. - it prints a string for each member of the collection (as a "side effect")
  90. - then the loop inside the print_names_and_emails method returns the user_array
  91. on which it was called
  92. - because this call of .each is the last thing that happens in the method, it's also,
  93. by default, what the method returns
  94. - calling UserIterator.new(users).print_names_and_emails also returns the original
  95. array of users with which we initialized the class instance
  96.  
  97. ------------------PRACTICING EACH exercise
  98.  
  99. herbs = ["lav","rose","basil"]
  100.  
  101. herbs.each do |herb|
  102. p herb.upcase
  103. end
  104.  
  105. # prints "LAV"\n, "ROSE"\n, "BASIL"\n
  106. # returns ["lav","rose","basil] - thanks to .each
  107.  
  108. ------------------THE EACH METHOD exercise
  109.  
  110. - again, .each returns the original array on which it's called.
  111.  
  112. - if we want to return the value from a method using .each,
  113. the trick is to store outputs of each iteration in a new array,
  114. then return that array.
  115.  
  116. - we'd need a local variable within the method body to collect
  117. the output of each iteration
  118. - we then return that variable by placing it on the last line, e.g.,
  119.  
  120. def what_number_are_we_on?(array)
  121. new_array = []
  122. # initialize new_array
  123. array.each do |num|
  124. new_array << "We're on number: #{num}"
  125. end
  126. # for each item in array, shovel the value into new_array
  127. new_array
  128. # return new_array
  129. end
  130.  
  131. - note that new_array must be declared as an empty array before we
  132. shovel items into it, else Ruby wouldn't know to treat it as an
  133. instance of the Array class.
  134.  
  135. - SPECS:
  136.  
  137. describe ArrayModifier do
  138. before do
  139. @array = ["Roxanne", "Put on the red light", "Roxanne", "Put on the red light"]
  140. end
  141.  
  142. describe '#exclaim' do
  143. it "adds an exclamation mark to each element" do
  144. exclaimed = ArrayModifier.new(@array).exclaim
  145. expect(exclaimed).to eq(["Roxanne!", "Put on the red light!", "Roxanne!", "Put on the red light!"])
  146. end
  147.  
  148. it "doesn't modify the original array" do
  149. original = @array.dup
  150. exclaimed = ArrayModifier.new(@array).exclaim
  151. expect(@array).to eq(original)
  152. end
  153. end
  154.  
  155. describe '#capsify' do
  156. it "uppercases each element" do
  157. capped = ArrayModifier.new(@array).capsify
  158. expect(capped).to eq(["ROXANNE", "PUT ON THE RED LIGHT", "ROXANNE", "PUT ON THE RED LIGHT"])
  159. end
  160.  
  161. it "doesn't modify the original array" do
  162. original = @array.dup
  163. capped = ArrayModifier.new(@array).capsify
  164. expect(@array).to eq(original)
  165. end
  166. end
  167. end
  168.  
  169. describe StringModifier do
  170. describe "#proclaim" do
  171. it "adds an exclamation mark after each word" do
  172. blitzkrieg_bop = StringModifier.new("Hey ho let's go").proclaim
  173. expect(blitzkrieg_bop).to eq("Hey! ho! let's! go!")
  174. end
  175. end
  176. end
  177.  
  178. - SOLUTION:
  179.  
  180. class ArrayModifier
  181. attr_accessor :array
  182. def initialize(array)
  183. @array = array
  184. end
  185. def exclaim
  186. new_array = []
  187. array.each do |string|
  188. new_array << "#{string}!"
  189. end
  190. new_array
  191. end
  192. def capsify
  193. new_array = []
  194. array.each do |string|
  195. new_array << string.upcase
  196. end
  197. new_array
  198. end
  199. end
  200.  
  201. class StringModifier
  202. attr_accessor :string
  203. def initialize(string)
  204. @string = string
  205. end
  206. def proclaim
  207. ArrayModifier.new(string.split(' ')).exclaim.join(' ')
  208. end
  209. end
  210.  
  211. ------------------EACH WITH INDEX exercise
  212.  
  213. - SPECS:
  214.  
  215. describe '#add_value_and_index' do
  216. it "returns a new array composed of the value + index of each element in the former" do
  217. expect( add_value_and_index([2,1,0]) ).to eq([2,2,2])
  218. end
  219. end
  220.  
  221. - SOLUTION:
  222.  
  223. def add_value_and_index(array)
  224. new_array = []
  225. array.each_with_index do |item,index|
  226. new_array << (item + index)
  227. end
  228. new_array
  229. end
  230.  
  231. ------------------TITLE CASE exercise
  232.  
  233. - SPECS:
  234.  
  235. describe "Title" do
  236. describe "fix" do
  237. it "capitalizes the first letter of each word" do
  238. expect( Title.new("the great gatsby").fix ).to eq("The Great Gatsby")
  239. end
  240. it "works for words with mixed cases" do
  241. expect( Title.new("liTTle reD Riding hOOD").fix ).to eq("Little Red Riding Hood")
  242. end
  243. it "downcases articles" do
  244. expect( Title.new("The lord of the rings").fix ).to eq("The Lord of the Rings")
  245. expect( Title.new("The sword And The stone").fix ).to eq("The Sword and the Stone")
  246. expect( Title.new("the portrait of a lady").fix ).to eq("The Portrait of a Lady")
  247. end
  248. it "works for strings with all uppercase characters" do
  249. expect( Title.new("THE SWORD AND THE STONE").fix ).to eq("The Sword and the Stone")
  250. end
  251. end
  252. end
  253.  
  254. SOLUTION:
  255.  
  256. class Title
  257. attr_accessor :string
  258. def initialize(string)
  259. @string = string
  260. end
  261. def fix
  262. prepositions = ["and","the","of","a"]
  263. array = string.downcase.split(' ')
  264. array.each_with_index do |item,index|
  265. if index==0 || !prepositions.include?(item)
  266. item.capitalize!
  267. end
  268. end
  269. array.join(' ')
  270. end
  271. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement