Skip to content

Instantly share code, notes, and snippets.

@JamesDullaghan
Created April 26, 2013 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesDullaghan/5464836 to your computer and use it in GitHub Desktop.
Save JamesDullaghan/5464836 to your computer and use it in GitHub Desktop.
ActiveRecord Schneems Arrays tutorial notes

#Arrays# ###Using the Docs###

[1,2,3,4].each {|x| puts x + 1 }
2
3
4
5
=> [1,2,3,4]

Some methods are aliased map => collect collect => map

Some methods take in optional arguements a = [11,12,13,14,15] puts a.first => 11

puts a.first(3)
=> [11,12,13]

Some Favorite Array methods!

  • each
  • map
  • map!
  • reject
  • select
  • detect
  • & (intersection)
  • [+] (concatenation)
  • << (insertion)
  • flatten
  • uniq
  • compact
  • first
  • last
  • count
  • each_with_object

a = ["a","s","c","d","d"]
a.count
=> 5
a.count {|x| x == "d"}
=> 2

Some might look alike, but some may have the "!" operator at the end. ! is called a bang in programming

a = ["a","b","c","b"]
b = a.map {|x| "foo:" + x }
puts b.inspect
=> ["foo:a", "foo:b", "foo:c", "foo:b"]
puts a.inspect
=> ["a","b","c","b"]

a hasn't changed at all, but if you wanted to change it, you could use map! to modify the original

b = a.map! {|x| x + "foo"}
puts a.inspect
=> ["foo:a", "foo:b", "foo:c", "foo:b"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment