Ruby Fundamentals Flashcards
The basics of the Ruby language
Ruby Basic Data Types
Numeric (Float or integer)
Boolean
String
Ruby Math Operators
- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Exponentiation: **
- Modulo: %
Ruby Assignment Operators
Normal Assignment:
i = <value></value>
Conditional Assignment:
i ||= <value>
(only assigns new value if i = nil)</value>
Numeric Modification Operators
Increment:
i += value
Decrement:
i -= value
Multiply:
i *= value
Divide:
i /= value
Output Methods
print “string”
prints string or value to screen
puts “string”
prints string or value and adds newline
Input Method
variable = gets
retrieves user input as a string
Note: adds a newline character which may need to be removed with String.chomp method:
variable = gets.chomp
Ruby File Extension
.rb
How is whitespace interpreted in Ruby
Whitespace is generally ignored.
Exceptions:
* White space in strings
* after method names, may treat the next value as a parameter being passed in
Ending statements or lines in Ruby
newline character and semicolon are both interpreted as the end of a current statement/line:
print “hello”
print “hello”;
Exception: lines ending with operator expect values in the next line:
print “hello “ +
“world”
String method to remove newline from end
.chomp
Example:
“Hello World\n”.chomp
returns “Hello World”
Calling Object Methods
Syntax:
object.method
or
object.method(parameter)
Modify calling object with method
Use the ! operator at the end of the method name:
object.method!
The object will be modified instead of a new object being returned
Single Line comment
Use the ‘#’ operator:
#this is a comment
Multiple Line Comments
=begin
this is
my comment
=end