Basic Ruby Flashcards
How to sum an Array?
array.inject(0, :+)
or
def sum(numbers) numbers.inject(0){|total, number| total+number} end
http://ruby-doc.org/core-1.9.3/Enumerable.html
How to multiply the elements of an array?
[1, 2, 3].inject(:*)
What is the Ruby power function?
2 ** 3 => 8
How to calculate a factorial?
(1..a).inject(:*) || 1
or
def factorial x if x <= 1 1 else x * factorial(x-1) end end
Ruby combining an array into one string?
Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):
@arr.join(“ “)
Extract first word from a string?
word.split(‘ ‘).first
Capitalize first letter in ruby?
def titleize(name)
name.capitalize
end
Ruby capitalize every word first letter.
def titleize(name) name.split.map(&:capitalize).join(' ') end
//don’t cap “the and over”
def titleize(s) words = s.split.map do |word| if %w(the and over).include?(word) word else word.capitalize end end words.first.capitalize! words.join(" ") end
map method
The map method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!):
[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]
Whats Iterator?
An iterator is a looping construct in Ruby. It uses method syntax. We optionally use an iteration variable, enclosed in vertical bars.
We invoke times, upto, downto, step and each. These are iterators.
Use a times-loop.
4.times do
puts “a”
end
# Go up from 3 to 5. 3.upto(5) do |x|
# Decrement from 5 to 3. 5.downto(3) do |j|
# Increment from 0 to 10, by 2 each time. # ... Name the iteration variable "v". 0.step(10, 2) do |v| puts v end
Ruby: what does %w(array) mean?
%w(foo bar) is a shortcut for [“foo”, “bar”].
What is Sprintf?
sprintf is pretty similar to printf. The major difference is that instead of printing to the screen, sprintf saves the formatted text into a string variable.
ternary operator
In Ruby, ? and : can be used to mean “then” and “else” respectively.
def check_sign(number) number > 0 ? "#{number} is positive" : "#{number} is negative" end
Filtering elements of an Array
# select even numbers [1,2,3,4,5,6].select {|number| number % 2 == 0}
Array Delete
[1,3,5,4,6,7].delete(5)
[1,2,3,4,5,6,7].delete_if{|i| i < 4 }