Mark's Ruby on Rails Cards Flashcards
string
Strings are used for storing and manipulating text in Ruby. Strings are written between quotation marks.
my_name = "Eric" that_computer = "Eric's Computer" #this is legal
booleans
In Ruby, there are two boolean values: true and false.
true
=> true
false
=> false
variables
Variables are assigned values using the = operator.
Syntax
variable_name = value
Example
name = “Artur”
=> “Artur”
name_copy = name
=> “Artur”
age = 21
=> 21
puts vs. print
The puts (short for “put string”) and print commands are both used to display the results of evaluating Ruby code. The primary difference between them is that puts adds a newline after executing, and print does not.
3.times { print “Hello!” }
Hello!Hello!Hello!
3.times { puts “Hello!” }
Hello!
Hello!
Hello!
Methods
A Ruby method is used to create parameterized, reusable code. Ruby methods can be created using the syntax:
Syntax
def method_name(arguments)
# Code to be executed
end
Example
def sum(x,y)
x + y
end
sum(13, 379)
=> 392
A method, then, is simply programming jargon for something one object can do for another.
Multi Line Command
You can write multi-line comments by starting the comment with =begin and finishing it with =end
Alternatively, each line can start with a #
gets
gets is the Ruby method that gets input from the user. When getting input, Ruby automatically adds adds a blank line (or newline) after each bit of input; chomp removes that extra line (Your program will work fine without chomp, but you’ll get extra blank lines everywhere
array
In Ruby, we can pack multiple values into a single variable using an array. An array is just a list of items between square brackets, like so: [1, 2, 3, 4]. The items don’t have to be in order—you can just as easily have [10, 31, 19, 400].
if
Ruby’s if statement takes an expression, which is just a fancy word for something that has a value (like 4, true, or pants). If that expression is true, Ruby executes the block of code that follows the if. If it’s not true (that is, false), Ruby doesn’t execute that block of code: it skips it and goes on to the next thing.
Here’s an example of an if statement in action:
if 1 < 2
print “I’m getting printed because one is less than two!”
end
unless
This is the opposite of an if statement. The statement takes a boolean expression and executes certain code only if the boolean expression evaluates to false.
Syntax
unless boolean_expression
#do something here
end
Example
hungry = true
unless hungry puts "I'm writing Ruby programs!" else puts "Time to eat!" end
elsif
A conditional statement used to manage a program’s control flow. The statement must be paired with an if or unless block and takes a boolean expression. It runs certain code only if the previous conditional statements do not run and its boolean expression evaluates to true. it is equivalent to writing an else statement that has an if statement in its block.
Syntax
if boolean_expression #do something elsif boolean_expression_2 #do something different else #do something else
Example
x = 5 if x > 5 print "I am big!" elsif x == 5 print "I am medium!" else print "I am small!" end
I am medium!
else
The partner to the if statement is the else statement. An if/else statement says to Ruby: “If this expression is true, run this code block; otherwise, run the code after the else statement.” Here’s an example:
if 1 > 2 print "I won't get printed because one is less than two." else print "That means I'll get printed!" end
environment
The collection of all variables and their values that exist in the program at a given time.
Control flow
Control flow gives us the flexibility we’re looking for. We can select different outcomes depending on information the user types, the result of a computation, or the value returned by another part of the program.
expression
Ruby’s if statement takes an expression, which is just a fancy word for something that has a value (like 4, true, or pants). If that expression is true, Ruby executes the block of code that follows the if. If it’s not true (that is, false), Ruby doesn’t execute that block of code: it skips it and goes on to the next thing.
Here’s an example of an if statement in action:
if 1 < 2
print “I’m getting printed because one is less than two!”
end
Ruby doesn’t care about whitespace (spaces and blank lines), so the indentation of the print statement isn’t necessary. However, it’s a convention that Rubyists (Ruby enthusiasts) follow, so it’s good to get in the habit now. The block of code following an if should be indented two spaces.
When you’re done with your if, you have to tell Ruby by typing end.
assignment operator
In Ruby, we assign values to variables using =, the assignment operator.But if we’ve already used = for assignment, how do we check to see if two things are equal? Well, we use ==, which is a comparator (also called a relational operator). == means “is equal to.” When you type
x = 2 y = 2 if x == y print "x and y are equal!" end
you’re saying: “if x equals y, print ‘x and y are equal!’” You can also check to see if two values are not equal using the == comparator.
comparator
how do we check to see if two things are equal?
Well, we use ==, which is a comparator (also called a relational operator). == means “is equal to.”
test_1 = 17 > 16
test_2 = 21 < 30
test_3 = 9 >= 9
test_4 = -11 < 4
Less Than or Greater Than
We can also check to see if one value is less than, less than or equal to, greater than, or greater than or equal to another. Those operators look like this:
Less than: <
Less than or equal to:
Greater than or equal to: >=
And
Comparators aren’t the only operators available to you in Ruby. You can also use logical or boolean operators. Ruby has three: and (&&), or (||), and not (!). Boolean operators result in boolean values: true or false.
The boolean operator and, &&, only results in true when both expression on either side of && are true. Here’s how && works:
true && true # => true
true && false # => false
false && true # => false
false && false # => false
For example, 1 < 2 && 2 < 3 is true because it’s true that one is less than two and that two is less than three.
The ‘While’ Loop
Ruby includes a while loop that will execute a block of code as long as its condition is true. When the condition becomes false, the code after the end of the loop will be executed.
Syntax
while condition_is_true # do something end
Example
i = 1 while i < 5 puts "#{i} is less than 5!" i += 1 end puts "Done!"
1 is less than 5! 2 is less than 5! 3 is less than 5! 4 is less than 5! Done!
Inclusive and Exclusive Ranges
You saw a bit of new syntax in the previous exercise: for num in 1…10. What this says to Ruby is: “For the variable num in the range 1 to 10, do the following.” The following was to print “#{num}”, so as num took on the values of 1 to 9, one at a time, those values were printed to the console.
for num in 1…10
puts num
end
The reason Ruby counted to 9 and not 10 was because we used three dots in the range; this tells Ruby to exclude the final number in the count: for num in 1…10 means “go up to but don’t include 10.” If we use two dots, this tells Ruby to include the highest number in the range.
iterator
An iterator is just a Ruby method that repeatedly invokes a block of code. The code block is just the bit that contains the instructions to be repeated, and those instructions can be just about anything you like!
not equal
!=
The boolean operator “and”
The boolean operator and, &&, only results in true when both expression on either side of && are true. Here’s how && works:
true && true # => true true && false # => false false && true # => false false && false # => false For example, 1 < 2 && 2 < 3 is true because it's true that one is less than two and that two is less than three.
The boolean operator “inclusive or”
Ruby also has the or operator (||). Ruby’s || is called an inclusive or because it evaluates to true when one or the other or both expressions are true. Check it out:
true || true # => true
true || false # => true
false || true # => true
false || false # => false
Not
Finally, Ruby has the boolean operator not (!). ! makes true values false, and vice-versa.
!true # => false
!false # => true
new line - tab - spaces
\n newline \t tab \s space
.each method
can apply an expression to each element of an object, one at a time. The syntax looks like this:
object.each { |item| # Do something }
You can also use the do keyword instead of {}:
object.each do |item| # Do something end
The variable name between | | can be anything you like: it’s just a placeholder for each element of the object you’re using .each on.
iterate
When we loop over an array or a hash, we say that we iterate over it.
return keyword
The return keyword specifies the object to be returned to the caller when the method has done its work.
literal notation
you give it a name and you set it equal to a bunch of key => value pairs inside curly braces.
agrument
The argument is the piece of code you actually put between the method’s parentheses when you call it
parameter
The parameter is the name you put between the method’s parentheses when you define it.
operand
(item to be compared)
combined comparison operator
The combined comparison operator looks like this: . It returns 0 if the first operand (item to be compared) equals the second, 1 if first operand is greater than the second, and -1 if the first operand is less than the second.
ternary conditional expression
An even more concise version of if/else is the ternary conditional expression. It’s called “ternary” because it takes three arguments: a boolean, an expression to evaluate if the boolean is true, and an expression to evaluate if the boolean is false.
boolean ? Do this if true: Do this if false
puts 3 < 4 ? “3 is less than 4!” : “3 is not less than 4.”
conditional assignment operator
We’ve seen that we can use the = operator to assign a value to a variable. But what if we only want to assign a variable if it hasn’t already been assigned? For this, we can use the conditional assignment operator: ||=. It’s made up of the or (||) logical operator and the normal = assignment operator.
Implicit Return
Ruby’s methods will return the result of the last evaluated expression.
.times method
If we want to do something a specific number of times, we can use the .times method, like so:
5.times { puts "Odelay!" } # Prints 5 "Odelay!"s on separate lines
.each method
If we want to repeat an action for every element in a collection, we can use .each:
[1, 2, 3].each { |x| puts x * 10 } # Prints 10, 20, 30 on separate lines
.upto & .downto
If we know the range of numbers we’d like to include, we can use .upto and .downto. This is a much more Rubyist solution than trying to use a for loop that stops when a counter variable hits a certain value.
We might use .upto to print out a specific range of values:
95.upto(100) { |num| print num, " " } # Prints 95 96 97 98 99 100
and we can use .downto to do the same thing with descending values.
.respond_to?
.respond_to? takes a symbol and returns true if an object can receive that method and false otherwise. For example:
[1, 2, 3].respond_to?(:push)
would return true, since you can call .push on an array object. However,
[1, 2, 3].respond_to?(:to_sym)
would return false, since you can’t turn an array into a symbol.