Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ruby learning
# Learning ruby, trying to remember these fun facts
#--ARRAYS
#--#--Useful functions
[1, 2, 3, 4].any? {|n| n > 2} #=> true
[1, 2, 3, 4].all? {|n| n > 2} #=> false
#--#--collect and map (collect! and map!)
a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" } #=> ["a!", "b!", "c!", "d!"]
a #=> ["a", "b", "c", "d"]
a.collect! {|x| x + "!" }
a #=> [ "a!", "b!", "c!", "d!" ]
#--#--reduce/inject
(5..10).reduce(:+) => 45
(5..10).inject {|sum, n| sum + n } => 45
(5..10).inject(1) {|product, n| product * n } #=> 151200
longest = %w{ cat sheep bear }.inject do |memo,word|
memo.length > word.length ? memo : word
end
#--#--reverse and reverse! and reverse_each
[ "a", "b", "c" ].reverse #=> ["c", "b", "a"]
a = [ "a", "b", "c" ]
a.reverse! #=> ["c", "b", "a"]
a #=> ["c", "b", "a"]
[ "a", "b", "c" ].reverse_each {|x| print x, " " } #=> c b a
#--#--rotate and rotate!
a = [ "a", "b", "c", "d" ]
a.rotate #=> ["b", "c", "d", "a"]
a #=> ["a", "b", "c", "d"]
a.rotate(2) #=> ["c", "d", "a", "b"]
a.rotate(-3) #=> ["b", "c", "d", "a"]
a = [ "a", "b", "c", "d" ]
a.rotate! #=> ["b", "c", "d", "a"]
#--#--sample and shuffle
#takes random sample or randomly shuffle
[1, 2, 3, 4, 5].sample #=> 2 #random
[1, 2, 3, 4, 5].sample(2) #=> [3, 5] #random
[1, 2, 3].sample(2) #=> [2, 3, 1] #random
#--#--select and select!
a = %w{ a b c d e f }
a.select {|v| v =~ /[aeiou]/} #=> ["a", "e"]
a.select! {|v| v =~ /[aeiou]/}
a #=> ["a", "e"]
#--#--Shift
# move an element from one end of array to other #rotate looks nicer
arr = [*1..5]
arr << ar.shift
#> arr => [2, 3, 4, 5, 1]
#--Enumerables
# works with all the same functions as array
%w{ant bear cat}.all? {|word| word.length >= 3}
%w{ant bear cat}.any? {|word| word.length >= 3}
%w{ant bear cat}.each do |word|
puts word.length
end
#--Conditional tricks
# conditional method definition:
def singleton_class
class << self
self
end
end unless respond_to?(:singleton_class) # exists in 1.9.2
# conditional assignment:
if p = some_method(args)
puts p #p exists, do stuff with p
end
unless p = some_method(args)
p = something(args) #p doesn't exist, do something
end
#-- Using unless
# try to only use unless when there are no negations
# and don't use it when there are multiple conditions
#good
unless foo?
puts 'no foo'
end
#bad
unless foo? && bar?
puts 'if not foo? or not bar?'
end
#bad - use if when there is an else condition
unless foo?
#something
else
#something
end
#--Method Definition
#returns nil by default, no need to explicitly return nil unless short-circuiting
def some_method
27 if false
end
#--Inheritance
# constants inherited and can override, works same way with methods
class A
P = 10
end
class B < A
P = 11
end
class C < A
end
B::P #=> 11
C::P #=> 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.