Last active
February 3, 2021 19:21
-
-
Save TutorialDoctor/dddb3663eb82370fd786529a11b71f87 to your computer and use it in GitHub Desktop.
Ruby Syntax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Coding | |
# https://ruby-doc.org/core-1.9.2/String.html | |
# http://www.peachpit.com/articles/article.aspx?p=1278994&seqNum=4 | |
def title1(name="") | |
puts "\n" + name.upcase + ":" | |
puts "-"*65 | |
end | |
#Note: '\n' doesn't create a new line. Must use "\n". | |
def title2(name="") | |
puts "\n" + name.capitalize | |
puts "-"*65 | |
end | |
def title3(name="") | |
puts "\n" + name | |
puts "-"*65 | |
end | |
def newline() | |
puts("\n") | |
end | |
#--------------------------------------- | |
title1("Ruby Syntax") | |
title3("https://gist.github.com/TutorialDoctor/dda76e58fc43d7375856") | |
#--------------------------------------- | |
# TABLE OF CONTENTS | |
# *** BEGINNER *** | |
=begin | |
PRINTING | |
INPUT | |
OPERATORS | |
COMMENTS | |
VARIABLES | |
FUNCTIONS | |
CONDITIONALS | |
LOOPS | |
CLASSES | |
MODULES | |
=end | |
# *** INTERMEDIATE *** | |
=begin | |
LIST COMPREHENSION | |
ARGUMENT PARAMETERS | |
KEYWORD ARGUMENTS | |
DOCSTRINGS | |
FILES | |
PARSING CSV FILES | |
DATA MODELS | |
=end | |
# *** ADVANCED *** | |
=begin | |
Comming soon | |
=end | |
# *** POPULAR MODULES *** | |
=begin | |
datetime | |
re | |
copy | |
pickle | |
os | |
socket | |
json | |
=end | |
#--------------------------------------- | |
puts "\n*** Beginner code follows this line: ***\n" | |
# *** BEGINNER *** | |
# PRINTING | |
title1('printing') | |
#--------------------------------------- | |
# Print a string | |
=begin | |
puts "Hello World" | |
print "Hello World" | |
# Print multiple strings | |
puts "Hello","World" | |
# Join/Concatenate two strings (gives errors if not strings) | |
puts "Hello" + "World" | |
# Joining two strings with spaces | |
puts "Hello" + " World" | |
# Printing numbers | |
puts 27 | |
# Another way to print (only way in python 3+) | |
puts("Hello World") | |
#I've updated the print statements in this script for python 3 users | |
# Print an empty line (useful for separating code output) | |
puts('') | |
=end | |
#--------------------------------------- | |
# INPUT | |
title1('input') | |
#--------------------------------------- | |
=begin | |
# Get number input (works for words and numbers) | |
puts gets.chomp("How old are you ") | |
puts gets("How old are you\n") | |
# Get word/string input | |
=end | |
#--------------------------------------- | |
# OPERATORS | |
title1('operators') | |
#--------------------------------------- | |
=begin | |
# Adding | |
puts(1+2) | |
# Subtracting | |
puts(4-3) | |
# Multiplying | |
puts(3*3) | |
# Dividing (not accurate if one of the terms isn't a decimal) | |
puts(18/3) | |
# Remainder/Modulus | |
puts(9%4) | |
# Power | |
puts(2**8) | |
# Suare root | |
puts(144**(1/2.0)) # must use at least one float | |
# Comparisons | |
puts(2<4) #less than | |
puts(4>9) #greather than | |
puts(5==6) #is equal to | |
puts(3==3) | |
puts(4!=4) #not equal to | |
puts(4!=9) | |
=end | |
#--------------------------------------- | |
# COMMENTS/NOTES | |
title1('comments') | |
#--------------------------------------- | |
=begin | |
A comment is a note for future or peer reference. The # symbol turns a line into a comment. Comments are not recognized as code, and are often used to disable bits of code. Tripple quotes are a multiline comment. They allow you to write comments that span multiple lines. | |
=end | |
#--------------------------------------- | |
# VARIABLES | |
title1('variables') | |
#--------------------------------------- | |
# Types | |
#--------------------------------------- | |
=begin | |
# Character | |
at = "@" | |
puts(at) | |
# String (wrapped in quotes) | |
name = "Raphael" | |
puts(name) | |
# Integer (no quotes quotes) | |
age = 29 | |
puts(age) | |
# Float | |
height = 6.3 | |
puts(height) | |
# Boolean | |
is_cool = TRUE | |
puts(is_cool) | |
# Array/List | |
array = [] #an empty array | |
array2 = Array.new #another way | |
array3 = Array[] #and another | |
array4 = Array(nil) #and another | |
colors = ["red","orange","yellow","green","blue","indigo","violet"] | |
numbers = [0,1,2,3,4,5,6,7,8,9] | |
mixed_array = [9,"alpha",63.3,TRUE] | |
puts array,colors,numbers,mixed_array | |
# Another way to create an array | |
# %W, or %w, with (most) any symbol will make an Array. | |
print %w^ 1,2,3^ | |
newline() | |
print %w@ 4,5,6@ | |
newline() | |
# Array by index | |
brr = [:a, :b, :c, :d] | |
brr[1] = 3 | |
print brr | |
newline() | |
# Auto fill | |
crr = [1,2,3] | |
crr[10] = :foo | |
print crr | |
newline() | |
#array methods are :pop and :push and the methods for adding and removing from the beginning of an Array are :shift and :unshift. | |
# Tuple | |
#location = Tuple(0,0) | |
#puts(location) | |
# Hash/Dictionary | |
dictionary = {} #empty dictionary | |
dictionary1 = Hash.new #another way | |
dictionary2 = Hash[] #and another | |
dictionary3 = Hash(nil) #and another | |
hash = Hash.new | |
hash[:book_name] = "I am the book" | |
puts hash[:book_name] | |
# Example 1 | |
x = {} | |
x.default = [] | |
puts x.default | |
x[:a] << 8 | |
x[:b] << 9 | |
x[:c] << 10 | |
print x.default | |
newline() | |
dictionary = {"key":"value"} | |
puts(dictionary) | |
# Set | |
#Set is an Array that enforces uniqueness | |
require 'set' | |
s = Set.new | |
s << :a | |
s << :a | |
s << :b | |
s << :c | |
s << :c | |
print s.to_a | |
newline() | |
# Struct | |
#a struct allows you to predefine what values you can set by providing keys when created. | |
#Example 1 | |
class Face < Struct.new(:hair, :eyes, :skin) | |
end | |
my_face = Face.new :blond, :blue, :awesome | |
# => #<struct Face hair=:blond, eyes=:blue, skin=:awesome> | |
my_face[:hair] | |
# => :blond | |
my_face.hair | |
# => :blond | |
print my_face | |
newline() | |
#Example 2 | |
class PayChecks < Struct.new(:week1, :week2, :week3, :week4) | |
def total | |
inject :+ | |
end | |
end | |
pay_checks = PayChecks.new 100, 800, 300, 45 | |
# => #<struct PayChecks week1=100, week2=800, week3=300, week4=45> | |
puts 'Paycheck total: '+pay_checks.total.to_s | |
# => 1245 | |
# OpenStruct | |
#openStruct is similar to Struct but is more “open”; more accepting. You will have to require it with require ‘ostruct’ . | |
#Example 1 | |
require 'ostruct' | |
x = OpenStruct.new | |
puts x[:a] | |
puts x | |
puts x[:a] = 0 | |
puts x | |
puts x.a | |
puts x.b | |
puts x | |
puts x[:b] = 123 | |
puts x | |
# Overwriting a variable | |
is_cool = FALSE | |
name = "Tutorial Doctor" | |
age = 10585 #in days | |
height = 6.1 | |
puts(is_cool,name,age,height) | |
# Set a boolean to the opposite of itself | |
is_cool = ! is_cool #False | |
puts(is_cool) | |
# Casting (changing the type of a variable) | |
# To a float | |
age = age.to_f | |
puts(age) | |
# To an integer | |
height = height.to_i | |
puts(height) | |
# To a string | |
is_cool = is_cool.to_s | |
puts(is_cool) | |
# Other Casting functions | |
#bool() #To a boolean | |
#.to_a #To a list | |
#.to_h #To a dictionary | |
#.to_c #To a complex | |
#.to_r #To a rational | |
#.to_regexp #To a regular expression | |
# Printing the type of a variable | |
puts is_cool.class | |
puts height.class,age.class,colors.class,dictionary.class | |
# Python keywords cannot be used as variable names. | |
# Variable names can't start with a number | |
# Variable names can't start with special characters | |
# Use undrescores or camelcasing to separate parts of a variable name | |
# ID of a variable | |
puts name.object_id | |
# Declaring multiple variables at once | |
a,s,l = 29,'Male','Georgia' | |
puts(a) | |
puts(s) | |
puts(l) | |
puts a,s,l | |
# Setting variables to same value at once | |
a=b=c = 45 | |
puts a,b,c | |
=end | |
#--------------------------------------- | |
# Strings | |
title2('strings') | |
#--------------------------------------- | |
=begin | |
# Empty string (two ways) | |
first_name = "" | |
last_name = '' | |
# Assign value to a string | |
first_name = "Raphael" | |
last_name = "Smith" | |
occupation = "Programmer" | |
# Adding strings (concatenation) | |
puts(first_name + last_name) | |
# Adding a space between string variables | |
puts(first_name + " " + last_name) | |
# Starting a new line (escape characters) | |
puts(first_name + "\n" + last_name) | |
# Escaping | |
message = "I\'m not old enough" | |
# The backslash escapes the apostrophe so it doesn't get inerpreted as a quote | |
puts(message) | |
# String Formatting (adding variables inside of a string) | |
puts("Hello #{first_name} #{last_name}") #string variables | |
# Number formatting | |
age = 29 | |
puts("I am #{age} years old") | |
#digit variable | |
puts("I am #{"%05d" % age} years old") | |
#leading zeros | |
puts("I am #{"%f" % age} years old") | |
#float | |
puts("I am #{"%.2f" % age} years old")#truncate decimal places | |
puts("I am #{"%.6f" % age} years old") #truncate | |
# Another way to format | |
greeting = "My name is #{first_name} and I am #{age} years old" | |
puts(greeting) | |
# Another way to use the format() function | |
greeting = "My name is #{name='Josiah'} and I am #{age=34} years old" | |
puts(greeting) | |
# Print a string several times | |
puts(first_name*10) | |
# Get an index of a string (indices start at 0) | |
puts(first_name[0]) #prints the fist item in the string | |
puts(first_name[1]) #prints the second item | |
# Indexing backwards | |
puts(first_name[-1]) #prints the last item in the string | |
puts(first_name[-2]) #prints the second to last item in the string | |
# Multi-line String | |
sentence = '''Multi-Line strings are sometimes used as multi-line comments, since python doesn\'t have syntax for multi-line comments. They are usually used for long strings of text, and as docstrings (strings at the beginning of functions that are used for documenting what the function does)''' | |
puts sentence | |
# More legal syntax | |
fourth_letter = "Python"[3] | |
puts(fourth_letter) | |
#--------------------------------------- | |
# String Functions | |
#--------------------------------------- | |
# Capitalize | |
name = "raphael" | |
bio = "My name is #{name}, how are you today?" | |
puts name.capitalize | |
# Uppercase | |
puts name.upcase | |
# Lowercase | |
puts name.downcase | |
# Length of string | |
puts name.length | |
# Split a string into individidual words | |
bio_words = bio.split # returns a list/array of the words | |
puts(bio_words) | |
# Joining split words into a single string | |
joined_words = bio_words.join(" ") | |
puts(joined_words) | |
# Replace items in a string | |
sentence = 'Jello, how are you today?' | |
corection = sentence.sub!('J','H') | |
puts(corection) | |
=end | |
# Integers | |
title2('integers') | |
#--------------------------------------- | |
=begin | |
timer = 0 | |
# Increment (Add 1 to the time variable) | |
timer = timer + 2 | |
# Another way | |
timer +=1 | |
puts(timer) | |
# Decrement (Subtract increment) | |
timer = timer - 1 | |
timer -=1 | |
puts(timer) | |
# Multiply increment | |
timer *= 10 | |
puts(timer) | |
# Divide Decrement | |
timer /= 2 | |
puts(timer) | |
=end | |
# Floats | |
title2('floats') | |
#--------------------------------------- | |
# Arrays | |
title2('arrays') | |
#--------------------------------------- | |
=begin | |
# Create an Array | |
inventory = ["flashlight","map","knife","string"] | |
clothes = ["shirt","pants","shoes","bandana","hat"] | |
# Get index of an array (starts at 0) | |
puts(inventory[0]) | |
# Get last item in array | |
puts(inventory[-1]) | |
# Array index range (starting at... up to...) | |
puts(inventory[1..4]) # 2nd to the fourth item | |
# Array index range (starting at...) | |
# Array index range (up to...) | |
#--------------------------------------- | |
# Array Functions | |
#--------------------------------------- | |
# Append to a array | |
inventory.push("rope") | |
puts(inventory) | |
# Remove from a array | |
inventory.delete('rope') | |
puts(inventory) | |
# Insert item at location | |
inventory.insert(0,"knife") | |
puts(inventory) | |
# Reverse Array | |
inventory.reverse() | |
puts(inventory) | |
# Sort a Array (alphabetical or numerical depending) | |
inventory.sort() | |
puts(inventory) | |
# Remove an item at a location | |
inventory.pop(1) | |
puts(inventory) | |
# Return the index of an item in the array | |
puts(inventory.index("rope")) | |
# Extend a array with another array | |
inventory.concat clothes | |
puts(inventory) | |
# Count how many times an item appears in a array | |
puts(inventory.count("knife")) | |
puts(inventory.count("rope")) | |
# Loop through a array | |
# Remove array from a arrat | |
=end | |
#--------------------------------------- | |
# Classes | |
# class Book | |
# attr_accessor :title, :author, :pages | |
# end | |
# b1 = Book.new | |
# b1.title = "Book 1" | |
# b1.pages = 400 | |
# puts b1.title | |
# puts b1.pages | |
# class NewBook | |
# attr_accessor :title, :author, :pages | |
# def initialize(title, author, pages) | |
# @title = title | |
# @author = author | |
# @pages = pages | |
# end | |
# end | |
# b1 = NewBook.new('Game','Me',500) | |
# puts b1.pages | |
# class Chef | |
# def make_chicken | |
# puts "Making some chicken for you" | |
# end | |
# def make_salad | |
# puts "Making some salad for you" | |
# end | |
# def make_special_dish | |
# puts "Making a special dish for you" | |
# end | |
# end | |
# class ItalianChef < Chef | |
# def make_special_dish | |
# puts "Making a special italian dish for you" | |
# end | |
# def make_pasta | |
# puts "Making some pasta for you" | |
# end | |
# end | |
# i_chef = ItalianChef.new() | |
# i_chef.make_chicken | |
# i_chef = ItalianChef.new() | |
# i_chef.make_special_dish | |
# MODULES | |
# module Tools | |
# def toolbelt | |
# puts "toolbelt tool" | |
# end | |
# end | |
# include Tools | |
# Tools.toolbelt | |
# module Rails | |
# class Application | |
# def initialize() | |
# puts "Created new application" | |
# end | |
# end | |
# end | |
# include Rails | |
# Rails::Application.new() | |
# module Gem1 | |
# def log | |
# puts 'Gem1: ...' | |
# end | |
# end | |
# module Gem2 | |
# def log | |
# puts 'Gem2: ...' | |
# end | |
# end | |
# class Logger | |
# include Gem1 | |
# include Gem2 | |
# end | |
# Logger.ancestors # => [Logger, Gem2, Gem1, Object, Kernel, BasicObject] | |
# #$ global vatiable | |
# $logger = Logger.new | |
# $logger.log # => 'Gem2: ...' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment