Ruby Arrays and Ashes

Hash

my_array = [[‘key1′,’value1’], [‘key2′,’value2’], [‘key3′,’value3’]]

my_hash = {}

my_array.each { |k,v| my_hash[k] = v }

=> [[“key1”, “value1”], [“key2”, “value2”], [“key3”, “value3”]]

Arrays

ordered,  integer-indexed collection of objects

Creating  arrays
  • arr=[]
  • arr=new(size, default)
  • arr=[number, ‘string’, :symbol]
Iterating through arrays

indexes starts at 0, negative index start from the end

.each iterator method (array unchanged)
arr.each { |e| puts e }
=> puts a[0], a[1], etc…

.collect iterator method (array changed) – same as .map
arr.collect { |e| e + ‘char’ }
=> returns modified elements

.select, .reject, .drop_while {|e| condition} .delete_if, keep_if
=> conditional selection, destructive with ! select!, reject!

indexing the array while iterating through
.each_with_index do |e, i|
puts “at position #{i}: #{e}”
end

iterate in reverse order – iterate with jumps
.reverse_each { |x| puts x }
.step(2) do |i|
puts “#{array[i]}” #iterate even indexes
end

custom  iterator – see this in Ruby Cookbook
class Array
def custom_iterator
new_array = []

return new_array
end

Enumerable – see all at Ruby Doc: Array
  • .index, rindex => index of occurrence: first, last
  • .length, .size=> size of array
  • .empty?=>any element there?
  • .include?(/regexp/)=>is this element there?
  • .uniq, .uniq! => removes duplicate, ! is destructive
    .sort => orders elements when all strings, numbers
    .shuffle => randomize elements
  • .min, .max => min and max elements
    .compact =>removes nils
  • .push (<<operator),  .unshift , .insert(index)=> adds to array: end, front, position
  • .pop, .shift => remove and retrieve object: first, last
  • .delete, .delete_at, .delete_if => deletes occurrence, by index, by condition
  • .slice, .slice! , find_all, grep /regexp/ => returns substring , ! returns object with string removed
Examples
Reject Duplicates when added to an array of unique elements
require ‘set’
survey_results = [1, 2, 7, 1, 1, 5, 2, 5, 1]
distinct_answers = survey_results.to_set
#<Set: {1, 2, 7, 5}>
distinct_answers << 5
=> nothing happens, duplicate is rejected

Custom Sort: Sort Elements by Size
arr=[[1,2,3,4], [1,2,3], [a,b], [a]]
.sort do |x,y|
x.size <=> y.size
end
=>[[“a”], [“a”, “b”], [1, 2, 3], [1, 2, 3, 4]]

 Tip: Numbers are sorted by value, and strings by  alphabetical order but lowercase characters precede uppercase characters.
More sorting example  in Ruby Cook Book
see: sort array of string ignoring case, sorted array remains sorted when modifying elements, sorting by frequency of appearances, shuffling,


Largest String in an Array of Strings
arr=[“”,”short”, “longer”,”much longer”]
arr.max { |x,y| x.size <=> y.size }
=>”much longer”

Building a Hash from an Array
arr.inject({}) do |hash, value|
hash[value.first] = value.last #builds the Hash element index => value
hash # necessary to call the hash itself to build the object
end

tip: use the .to_h method
customize  how keys in the array are mapped to values:

a.to_h { |value| [value * -1, value * 2] }
# => {1=>[-1, 2], 2=>[-2, 4], 3=>[-3, 6]}