Cookbook :: Ruby
As I go through and Learn Ruby. Here are some of my notes.
Notes on watching the YouTube video Ruby Programming Language.
Working With Strings.
33:13
String Methods, sometimes called. “String Functions”. String methods are little blocks of code that modify or give information about a string. Methods act on strings and allow you to modify the string contents or find out information about them. Google for “Ruby String Methods.” - For a list of methods you can use with strings.
More Resources on other String Methods.
string = "content"
puts string.upcase() #- Changes everything in string to uppercase.
puts string.downcase() #- Changes everything in string to lowercase.
puts string.strip() #- Leading and trailing whitespace gets deleted.
puts string.size #- Tell me how many characters are inside a string. (Including whitespace.)
puts string.include?("content") #- Returns a Boolean true or false if the string contains the word content.
puts string[0] #- Access the first character of the string a 'c' in this case.
puts string[0,3] #- Access a range of characters in a string.
puts string.index("c") #- Return index position number of the character 'c' in the string.
puts "content".upcase() #- Methods work on both variables or strings directly.
Math & Numbers.
44:03
Working with and using basic numbers.
puts 5 #- Prints out the number 5.
puts 5.123 #- Prints out the decimal number 5.123.
puts -5.123 #- Prints out negative numbers.
Basic Arithmetic.
puts 5 + 9 #- Addition. => 14
puts 5 - 9 #- Subtraction. => -4
puts 5 * 9 #- Multiplication => 45
puts 5 / 9 #- Division => 0
puts 5 ** 3 #- Exponential. (5 to the power of 3) => 125
puts 10 % 3 #- Modulus Operator. (10 divided by 3 spit out the remainder.) => 1
num = 20
puts num
Numbers can be stored inside of a variable.
num = 20
puts ("My favorite number is :" + num.to_s) #- The .to_s converts the number into a string.
Numbers and strings can be printed out inside the same print statement.
In addition to working with standard numbers. We can also use something called a method. A method is a block of code we can call that will either modify the number or give information about the number. Sometimes a method can also do mathematical calculations on the number.
num = -20
puts num.abs() #- Give me the absolute value of a number. Without the negative. => 20
Method to find the absolute value of a number. The absolute value of a number is never negative.
num = 20.487
puts num.round() #- Will round the number. => 20
num = 20.648
puts num.round() #- Rounding a number. => 21
Method to round a number.
num = 20.1
puts num.ceil() #- Will give us the highest number. => 21
num = 20.9
puts num.floor() #- Returns the lowest number. => 20
Ceiling and floor methods, are also referred to as functions. Ceiling will always take the higher number. Floor will always take the lower number.
puts Math.sqrt(36) #- Square root method. => 6
puts Math.log(1) #- Logarithmic. => 0.0
Other special methods from within math class. There is this ‘entity’ inside of ruby called math class that can be used to perform special math operations on numbers. Inside the Math class, there are methods.
Math Constants.
Source: Math Functions and Methods
Math.constants #- The ones currently defined are. => ["PI", "E"]
A list of constants can be accessed by using the constants method.
Math::PI #- Prints out pi. => 3.14159265358979
Math::E #- Prints out E. => 2.71828182845905
We can access these constants using the :: notation.
Ruby Math Methods.
Method Name | Description |
---|---|
Math.acos, Math.acos! | Arc cosine |
Math.acosh, Math.acosh! | Hyperbolic arc cosine |
Math.asin, Math.asin! | Arc sine |
Math.asinh, Math.asinh | Hyperbolic arc sine |
Math.atan, Math.atan!, Math.atan2, Math.atan2! | Arc tangent. atan takes an x argument. atan2 takes x and y arguments |
Math.atanh, Math.atanh! | Hyperbolic arc tangent |
Math.cos, Math.cos! | Cosine |
Math.cosh, Math.cosh | Hyperbolic cosine |
Math.sin, Math.sin! | Sine |
Math.erf | Error function |
Match.erfc | Complementary error function |
Math.exp, Math.exp! | Base x of Euler |
Math.frexp | Normalized fraction and exponent |
Math.hypot | Hypotenuse |
Math.ldexp | Floating-point value corresponding to mantissa and exponent |
Math.sinh, Math.sinh! | Hyperbolic sine |
Math.sqrt, Math.sqrt! | Square root |
Math.tan, Math.tan! | Tangent |
Math.tanh, Math.tanh! | Hyperbolic tangent |
Ruby provides a range of math related methods.
Working with Integer and Floating point numbers.
There is two basic types of numbers in ruby. Integer numbers. - Whole numbers. => 20 or 21 or 22 etc. Decimal numbers. => 22.1 or 22.5 or 22.7 etc. Integers and floats can be used inside ruby ‘basically interchangeably’, there are however two separate types. Ruby does distinguish between these two types. Whole Numbers - Floating Point Numbers.
puts 1 + 7 #- Will get an integer back. => 8
puts 1.0 + 7 #- Will get a floating point number back. => 8.0
Examples of working with both.
puts 10 / 7 #- Two integers are used, an integer is returned. => 1
puts 10 / 7.0 #- The full number is returned, because a floating point was used. => 1.4285714285714286
Whenever you add, multiply, divide, etc. two integers together you always get an integer back. Whenever you use an integer and a floating point number together to do some operation your always going to get a floating point back.
Getting User Input.
53:54
Allow a user to input information into the program. Store whatever is input into a variable. Print out that variable along with a message.
puts "Enter Your Name: " #- A prompt to tell the user what I want them to enter.
name = gets.chomp() #- Set the variable name to whatever the user enters. <= 'Enter Name.'
puts ("Hello " + name + ", you are cool.") # Print out the variable name added to the string Hello.
There is a special command in ruby called gets, this command allows a user to enter a piece of information into the program. Store whatever the user enters into the variable name.
When enter is used on a gets command. It automatically inserts a new line. use
get.comp()
to remove new line. ‘.chomp()’ gets rid of the new line character.
Building a Calculator.
1:01:09
Example calculator.
puts "Enter a number: "
num1 = gets.chomp()
puts "Enter another number: "
num2 = gets.chomp()
puts (num1 + num2)
When you enter anything into ruby, ruby automatically assumes its a string. This example. “Concatenates the strings.” We need to convert those strings into numbers using ‘.to_i’ to convert to an integer.
puts "Enter a number: "
num1 = gets.chomp()
puts "Enter another number: "
num2 = gets.chomp()
puts (num1.to_i + num2.to_i)
Ruby is taking whatever is inside num1 and num2 and converting it into an integer.
puts "Enter a number: "
num1 = gets.chomp()
puts "Enter another number: "
num2 = gets.chomp()
puts (num1.to_f + num2.to_f)
To convert to a floating point use. ‘.to_f’
puts "Enter a number: "
num1 = gets.chomp().to_f
puts "Enter another number: "
num2 = gets.chomp().to_f
puts (num1 + num2)
Alternative syntax.
Arrays
1:12:45
An array can hold multiple values.
friends = Array[1, "Karen", true] #- Array holding three Elements. A number, a String, and a Boolean.
puts friends #- Prints out the whole array.
puts friends[1] #- To access just one element of the array. With an index inside the [] => Karen
puts friends[-2] #- An array elements can also be accessed from the back of the array using negative indices. => Karen
puts friends[0, 2] #- To grab a range of elements. "Grab index position 0 all the way up to but not including 2." > 1, Karen
friends[0] = "Drew" #- To change the element in the array.
name = Array.new #- Telling ruby that we want the variable friends to be an array. Used when the elements to be put into the array are initially unknown.
name[0] = "Jack" #- First element.
name[5] = "Jill" #- Last element.
# Elements 2, 3, 4 are still blank.
# Methods on arrays.
puts friends.length() #- Tell me how many elements are inside the array.
puts friends.include?("Karen") #- Check the array to see if there is an element called "Karen." => Bool : True
puts friends.reverse() #- Reverse all the elements in the array.
# Sorting.
people = Array["Tony", "Bob", "Jack"]
puts people.sort() #- Sort the array alphabetically. # NOTE: Can't sort arrays that are multiple data types, including nil.
Hashes
1:21:31
Hashes store a key value pair. (Also called “dictionary’s”)
states = {
"Pennsylvania" => "PA",
"New York" => "NY",
"Oregon" => "OR"
}
puts states #- Prints out the structure. => {"Pennsylvania"=>"PA", "New York"=>"NY", "Oregon"=>"OR"}
puts states["Oregon"] #- Print out individual element for a key. => OR
# Alternative notation for defining an array key.
states = {
:Pennsylvania => "PA",
"New York" => "NY",
"Oregon" => "OR"
}
puts states[:Pennsylvania]
# Numbers can also be used as key's. ex. 1 => "PA",
Can only have unique keys.
Differences between a hash and an array. An array is basically a list of values that are accessed by an index number. An array is a list of key value pairs where the value is accessed by the name of the key.
Methods
1:27:42
Methods are blocks of code that perform a specific function. You can give methods information and they can give information back. Another name for a method is a function. In Ruby it basically means the same.
#- Define the method sayhi.
def sayhi
puts "Hello User"
end
#- Call the method sayhi.
sayhi
def sayhi(name="Default Name", age=-1)
puts ("Hello " + name + ", you are " + age.to_s)
end
sayhi("Mike", 23)
Specifying parameters. Default parameters can also be assigned and used if nothing is passed in the call.
Return Statement
1:35:28