Mercurial > repos > other > SevenLanguagesInSevenWeeks
diff 1-Ruby/day2.rb @ 19:ddcd809319ac
Add first two Day 2 exercises
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Wed, 04 Jan 2017 21:01:13 +0000 |
parents | |
children | 25c15f27b33d |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/1-Ruby/day2.rb Wed Jan 04 21:01:13 2017 +0000 @@ -0,0 +1,61 @@ +#! /usr/bin/env ruby + +## File handling with a block +name = 'day2.txt' + +def print_file(name) + File.open(name, 'r') do |file| + puts name + while line = file.gets + puts " #{line}" + end + end +end + +File.open(name, 'w') do |file| + file.puts "File contents go here" +end +print_file(name) +File.open(name, 'r+') do |file| + # If we don't seek then we override + file.seek(0, IO::SEEK_END) + file.puts 'Extra content here' +end +print_file(name) +File.delete(name) + +puts "File still exists!" if File.exists?(name) + +# Old-skool Java style without passing a code block +my_file = File.open(name, 'w') +my_file.puts 'Non-block file content' +my_file.close() #Note: Close the file manually! +print_file(name) +File.delete(name) + +## Converting a hash into an array +my_hash = { 'a' => 'one', 'b' => 'two', 'c' => 'three' } +puts my_hash.inspect +# "{}.methods" includes "to_a" method - appears to convert to an array. +puts my_hash.to_a.inspect +# However, it includes keys *and* values (as nested arrays, according to http://apidock.com/ruby/Hash/to_a). +# There's also ":keys" and ":values" +puts my_hash.keys.inspect +puts my_hash.values.inspect +# Alternatively, :collect runs over all key-value pairs as an array, so we can do: +puts my_hash.collect { |val| val[1] }.inspect + +## Converting an array to a hash +# Arrays have a :to_h method, but that assumes nested arrays of key-value pairs, +# e.g. [[key1, value1], [key2, value2]] +# Looping to create a nested array structure then :to_h would work: +my_array = ['one', 'two', 'three'] +temp = [] +# This would be neater with :map or :collect but then we don't get the index. +# The only sensible option is an :each_with_index, but that negates the need +# for :to_h. +my_hash = {} +my_array.each_with_index do |val, idx| + my_hash[idx] = val +end +puts my_hash.inspect