Basic Ruby Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

How to sum an Array?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to multiply the elements of an array?

A

[1, 2, 3].inject(:*)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the Ruby power function?

A

2 ** 3 => 8

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to calculate a factorial?

A

(1..a).inject(:*) || 1

or

def factorial x
  if x <= 1
    1
  else
    x * factorial(x-1)
  end
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Ruby combining an array into one string?

A

Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

@arr.join(“ “)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Extract first word from a string?

A

word.split(‘ ‘).first

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Capitalize first letter in ruby?

A

def titleize(name)
name.capitalize
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Ruby capitalize every word first letter.

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

map method

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Whats Iterator?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Ruby: what does %w(array) mean?

A

%w(foo bar) is a shortcut for [“foo”, “bar”].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is Sprintf?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

ternary operator

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Filtering elements of an Array

A
# select even numbers
[1,2,3,4,5,6].select {|number| number % 2 == 0}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Array Delete

A

[1,3,5,4,6,7].delete(5)

[1,2,3,4,5,6,7].delete_if{|i| i < 4 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Iterating over a Hash

A

restaurant_menu = { “Ramen” => 3, “Dal Makhani” => 4, “Coffee” => 2 }
restaurant_menu.each do |item, price|
restaurant_menu[item] = price + (price * 0.1)
end

17
Q

Extracting the keys and values from a Hash

A

restaurant_menu.keys

18
Q

Splat Operator

A
The splat operator is used to handle methods which have a variable parameter list.
def add(*numbers)
19
Q

Lambda

A

Function without a name. anonymous function.

addition = lambda {|a, b| return a + b }
puts addition.call(5, 6)

20
Q

Namespaces

A

Namespacing is a way of bundling logically related objects together. Modules serve as a convenient tool for this. This allows classes or modules with conflicting names to co-exist while avoiding collisions.

module Perimeter
  class Array
    def initialize
      @size = 400
    end
  end
end
our_array = Perimeter::Array.new
ruby_array = Array.new
p our_array.class
p ruby_array.class
21
Q

Block

A

A block is code that you can store in a variable like any other object and run on demand.

22
Q

Proc

A

Proc.new behaves like it’s a part of the calling method when return is used within it, and returns from both the block itself as well as the calling method.

short = proc { |a, b| a + b }
puts short.call(2, 3)

long = Proc.new { |a, b| a + b }
puts long.call(2, 3)

23
Q

Yield

A

???

24
Q

Converting implicit blocks to explicit

A

The block should be the last parameter passed to a method.
Placing an ampersand (&) before the name of the last variable triggers the conversion.

def calculation(a, b, &block) # &block is an explicit (named) parameter
block.call(a, b)
end

puts calculation(5, 5) { |a, b| a + b } # this is an implicit block
                                        # -- it is nameless and is not 
                                        # passed as an explicit parameter.
25
Q

3 Ways to create a block.

A

Implicitly when invoking a method
Explicitly using the Kernel#lambda factory method
Explicitly using Proc.new

The -> literal form is a shorter version of Kernel#lambda. The following two lines produce identical results.

26
Q

Super

A

Using super will call the same method, but as defined in the superclass and give you the result.