Permalink
Cannot retrieve contributors at this time
114 lines (46 sloc)
1.8 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # basics | |
| while true | |
| puts "'looped' one iteration by design" | |
| var1 = gets | |
| break # break out of the otherwise infinite loop | |
| end | |
| while true | |
| puts "This will loop forever!" | |
| var1 = gets | |
| next # got to the next iteration of the infinite loop | |
| break | |
| end | |
| for i in 0..5 | |
| puts "Value of local variable is #{i}" | |
| end | |
| a = [1, 2, 3] # make an array | |
| a.each do |element| | |
| puts element # loop through each element within the array | |
| end | |
| a.each { |element| | |
| puts element # Same thing but with brackets | |
| } | |
| a.each { |element| puts element} # same thing but on one line | |
| a.map { |element| element.to_s + " hi"} # woah, big difference! This one returns an array of length == a.length | |
| => ["1 hi", "2 hi", "3 hi"] | |
| a.map { |element| element.to_s + " yo"} # woah! and the contents of each array slot are the return of the block... | |
| => ["1 yo", "2 yo", "3 yo"] # (e.g. element.to_s + " hi") | |
| a.map(&:to_s) # shortened up drastically, but less flexable | |
| # notice | |
| User.first.following.map(&:id) | |
| => [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, | |
| 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, | |
| 43, 44, 45, 46, 47, 48, 49, 50, 51] | |
| a.map do |element| | |
| puts element | |
| end | |
| a = ["1", "", "2", "3", "", nil] | |
| a.compact # loops through and kicks out all the nil members | |
| => ["1", "", "2", "3", ""] | |
| a.reject(&:empty?) # loops through the array and kicks out all the empty members | |
| => ["1", "2", "3"] | |
| a = [1, 2, 3] | |
| out = [] | |
| a.each.with_index do |element, i| # loops through, but gives you the index variable | |
| out[i] = element # so you don't manually have to create and incriment it | |
| end | |