diff 1-Ruby/arrays.rb @ 14:9aa1eba404f0

Add some poking of arrays
author IBBoard <dev@ibboard.co.uk>
date Tue, 03 Jan 2017 20:28:17 +0000
parents
children 8d46064c9afc
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/1-Ruby/arrays.rb	Tue Jan 03 20:28:17 2017 +0000
@@ -0,0 +1,24 @@
+#! /usr/bin/env ruby
+
+animals = ['lions', 'tigers', 'bears']
+
+# Default "puts" for array is one element per line
+puts animals
+
+puts "Accessing undefined indexes gives nil" if animals[10] == nil
+puts "Negative indexes also work (like Python): -1 =  #{animals[-1]}"
+puts "And you get slices/ranges: 1..2 = #{animals[1..2]}"
+puts "1..2 is even an object: #{(1..2).class}"
+puts "and indexers are methods: [1].methods.include?(:[]) = #{[1].methods.include?(:[])}"
+# Note: we're using v1.9+ syntax - previously it was "….include?('[]')"
+puts "as is assignment to an array! [1].methods.include?(:[]=) = #{[1].methods.include?(:[]=)}"
+puts ""
+puts "All funky non-ASCII methods for arrays:"
+[].methods.each { |method| 
+	if method !~ /[a-z]/
+		puts method
+	end
+}
+
+puts ""
+puts "Arrays are also stacks with push() and pop() methods!"