Look up Ruby motions by running :help ruby-motion
.
command | effect |
---|
arr = [1, 2, 3, 4] | |
new_arr = arr.map { |x| x * 3 } | |
puts new_arr.inspect # => [3, 6, 9, 12] |
class Gear | |
attr_reader :chainring, :cog, :rim, :tire | |
def initialize(chainring, cog, rim, tire) | |
@chainring = chainring | |
@cog = cog | |
@rim = rim | |
@tire = tire | |
end | |
def ratio |
array = [1, 2, 3, 4] | |
array.collect! do |n| | |
n ** 2 | |
end | |
puts array.inspect # => [1, 4, 9, 16] |
cube = Proc.new { |x| x ** 3 } | |
[1, 2, 3].collect!(&cube) #=>[ 1, 8, 27] | |
[4, 5, 6].map!(&cube) #=>[64, 125, 216] |
lambda { puts "Hello!" } | |
#Is just about the same as | |
Proc.new { puts "Hello!" } |
lam = lambda { |x| puts x } # creates a lambda that takes 1 argument | |
lam.call(2) # prints out 2 | |
lam.call # ArgumentError: wrong number of arguments (0 for 1) | |
lam.call(1,2,3) # ArgumentError: wrong number of arguments (3 for 1) |
proc = Proc.new { |x| puts x } # creates a proc that takes 1 argument | |
proc.call(2) # prints out 2 | |
proc.call # returns nil | |
proc.call(1,2,3) # prints out 1 and forgets about the extra arguments |