Skip to content

Instantly share code, notes, and snippets.

@PamBWillenz
Last active August 29, 2015 14:18
Show Gist options
  • Save PamBWillenz/2a01c8472995995953bb to your computer and use it in GitHub Desktop.
Save PamBWillenz/2a01c8472995995953bb to your computer and use it in GitHub Desktop.
Basic Ruby Syntax
Strings are declared by placing quotes around a word. "Hello World"
A command is needed to instruct the computer to do something with the "hello world" string. As we mentioned in the checkpoint, Ruby has a command called p which prints the value of an object - p "hello world"
Booleans, Symbols and Variables - primitive data, just strings and numbers
Underscores make variables easier to read. When underscores are used in this capacity it's known as using "snake-case". The other type of case that you'll see in programming is "camel-case", which looks like: ThisIsCamelCase.
Symbols are like strings, only with less functionality. A Symbol is designated with a colon (:) to the left of a word. Symbols can contain any alpha-numeric character, but they must start with a letter.
Math Operations - Greater Than and Less Than
Basic math operations like + and * return numbers, but the > and < operators return boolean values. Type the following and keep your eyes on the return values:
> and < are comparison operators, and therefore return true or false. Another comparison operator is ==. Whereas the single = sign assigns a value, the == compares two values. Type the following to see how == works
hello = "hello"
p hello * 3
p hello + " world"
hello world
Output
"hellohellohello"
"hello world"
While "hello" + 3 doesn't make sense, you can mix strings and numbers if the return is meant to be an alpha-numeric string. Combining strings and numbers is called string interpolation. String interpolation is the act of inserting a non-string value into a String, thus resulting in a new String. Interpolation is accomplished with this #{ } syntax. Try it for yourself:
p "hello #{3}"
num = 5
p "hello #{num}"
Result
hello 5
Output
"hello 3"
"hello 5"
p "3 + 4 = #{3 + 4}"
num1 = 3
num2 = 4
p "3 + 4 = #{num1 + num2}"
Result
3 + 4 = 7
Output
"3 + 4 = 7"
"3 + 4 = 7"
Staying DRY
You can make this code a little cleaner though. In the example below take note of the difference when the num1 and num2 variables are used by themselves (#{num1}) as opposed to in an operation (#{num1 + num2}).
num1 = 3
num2 = 4
p "#{num1} + #{num2} = #{num1 + num2}"
Why is the second example better? In programming this is called "staying DRY". DRY stands for "do not repeat yourself." The reason why DRY code is better is because it's easier to maintain. For example, if you wanted to change the program to use 5 and 6 instead of 3 and 4, you would only need to change each variable assignment (num1 and num2), and not the interpolated string. In the first example, you'd have to change the variable assignments as well as the interpolated string (in four places).
Interpolated strings must be enclosed in double quotes. The Ruby interpreter will not search for interpolated values in a string if single quotes are used:
Compound Interest programs
# principal amount
principal = 10_000
# annual rate of interest
rate = 0.05
# number of years
time = 5
# number of times it is compounded
num = 12
# amount accumulated
amount = principal * (1 + rate/num) ** (num*time)
p "After #{time} years I'll have #{amount} dollars!"
Result
After 5 years I'll have 12833.586785035119 dollars!
Output
"After 5 years I'll have 12833.586785035119 dollars!"
NIL -
Square brackets ([]) are used in Ruby to reference locations. When you typed "Bloc"[7] you instructed Ruby to return the 7th character in the "Bloc" string. As you know, this operation returned nil because there is no 7th character in the "Bloc" string.
Notice that "Bloc"[2] returned o. You instructed Ruby to return the 2nd character in the "Bloc" string, so why didn't it return l? The reason is that counting starts at 0 in programming languages. This means that "Bloc"[0] would return B.
nil is different from 0 or a blank string (""). nil is simply an object in Ruby that represents nothingness.
METHODS
f you wanted to reuse a line of code in this respect, you'd have to type it in again. In programming, methods (often called functions) allow you to write code for reuse. To effect the same behavior, you just "call" the method. Before exploring methods, take note of two common terms used around methods in programming:
Call - run or execute a method.
Define - compose or write a method.
Method definition requires a specific structure in Ruby. Write your first Ruby method by typing:
def hello
"Hello world"
end
def return_three
a = 1
b = 2
a + b
end
p return_three
Result
3
Output
3
INTERACTING WITH METHODS
You can interact with methods by providing them with information. Consider two more terms around methods:
Argument - information given to a method.
Pass - provide a method with information (an argument).
There are two arguments passed to the method below. The arguments are named a and b.
def add(a,b)
a + b
end
An argument
def add(a,b)
a + b
end
p add(1,2)
p add(4,5)
p add(7,7)
Result
14
Output
3
9
14
# num = number of times compounded
def compound_interest(name, principal, rate, years, num)
amount = principal * (1 + rate/num) ** (num * years)
"After #{years} years, #{name} will have #{amount} dollars!"
end
p compound_interest("Bob", 100, 0.05, 40, 12)
p compound_interest("Joe", 250, 0.06, 50, 12)
Result
After 50 years, Joe will have 4983.988855879855 dollars!
Output
"After 40 years, Bob will have 735.8417318419806 dollars!"
"After 50 years, Joe will have 4983.988855879855 dollars!"
MY EXAMPLE:
Create a method named link which takes two arguments named address and text. The method should use these two arguments to return the HTML code needed to render a clickable link.
Hint: Your solution will look similar to the last line of code in the compound_interest method definition where we are "interpolating" variables into a string.
A properly implemented link method should be called like this:
p link("www.mysite.com", "My Site!")
and would print this:
"<a href='www.mysite.com'>My Site!</a>"
def link(address, text)
"<a href='#{address}'>#{text}</a>"
end
p link("www.mysite.com", "Not My Site!")
Result
<a href='www.mysite.com'>Not My Site!</a>
Output
"<a href='www.mysite.com'>Not My Site!</a>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment