Mercurial > repos > other > SevenLanguagesInSevenWeeks
changeset 20:25c15f27b33d
Complete iteration tasks for day 2
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sat, 07 Jan 2017 20:36:03 +0000 |
parents | ddcd809319ac |
children | 7e212cc7ec24 |
files | 1-Ruby/day2.rb |
diffstat | 1 files changed, 48 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/1-Ruby/day2.rb Wed Jan 04 21:01:13 2017 +0000 +++ b/1-Ruby/day2.rb Sat Jan 07 20:36:03 2017 +0000 @@ -59,3 +59,51 @@ my_hash[idx] = val end puts my_hash.inspect + +## Iterating a hash +puts "Each with single parameter gets pairs" +my_hash.each { |vals| puts "++#{vals[0]} = #{vals[1]}" } +puts "Each with two parameters gets key and value" +my_hash.each { |key, val| puts "++#{key} = #{val}" } +puts "Or you can get just keys and just values" +my_hash.each_key { |key| puts "++#{key}" } +my_hash.each_value { |value| puts "++#{value}" } + +## Arrays as stacks: +my_arr = [] +my_arr.push(1) +my_arr.push(2) +my_arr.push(3) +my_arr.push(4) +puts my_arr.pop() +puts my_arr.pop() +puts my_arr.pop() +puts my_arr.pop() +## Arrays as queues +my_arr.push(7) +my_arr.push(8) +my_arr.push(9) +my_arr.push(10) +puts my_arr.shift() +puts my_arr.shift() +puts my_arr.shift() +puts my_arr.shift() + +## Iterating in fours + +my_arr = Array(1..16) +# We need a temp place holder - we can't do ugly things with indexes +temp = [] +my_arr.each do |val| + temp.push(val) + if temp.size == 4 + puts "#{temp[0]} #{temp[1]} #{temp[2]} #{temp[3]}" + temp = [] + end +end + +## And with each_slice +my_arr.each_slice(4) do |val| + puts "#{val[0]} #{val[1]} #{val[2]} #{val[3]}" +end +