Ruby On Rails Flashcards
Studying
Ask name & print “Hello, _____!”
print “What’s your name ?”
name = gets.chomp
p “Hello, #{name}!”
\t
\s
tab in Ruby. ie. “Bob\tDoe” prints
“Bob Doe”
space in Ruby ie. “Bob\sDoe” prints
“Bob Doe”
.split
divides string into substrings, returning an array of these substrings. ie:
“ now’s the time”.split #=> [“now’s”, “the”, “time”]
“ now’s the time”.split(‘ ‘) #=> [“now’s”, “the”, “time”]
“ now’s the time”.split(/ /) #=> [””, “now’s”, “”, “the”, “time”]
“1, 2.34,56, 7”.split(%r{,\s}) #=> [“1”, “2.34”, “56”, “7”]
“hello”.split(//) #=> [“h”, “e”, “l”, “l”, “o”]
“hello”.split(//, 3) #=> [“h”, “e”, “llo”]
“hi mom”.split(%r{\s}) #=> [“h”, “i”, “m”, “o”, “m”]
“mellow yellow”.split(“ello”) #=> [“m”, “w y”, “w”]
“1,2,,3,4,,”.split(‘,’) #=> [“1”, “2”, “”, “3”, “4”]
“1,2,,3,4,,”.split(‘,’, 4) #=> [“1”, “2”, “”, “3,4,,”]
“1,2,,3,4,,”.split(‘,’, -4) #=> [“1”, “2”, “”, “3”, “4”, “”, “”]
«HERE
(HERE document)
Great for adding large sets of text.
Ie. words = <<HERE Now is the time for all people to come together. HERE
print words
Now is the time
for all people
to come together.
.include?
Does something include?
Ie. letters = ‘a’..’z’
letters.include?(‘h’)
=> true
.squeeze
Removes trailing spaces.
Ie. name = “Jane “
name.squeeze returns “Jane “
.each
Will return each piece of data within object called. Ie. range = (0..4) range.each {|n| puts n} 0 1 2 3 4
.to_a
Turns data into an array.
Ie. digits = 0..3
num_array = digits.to_a
=> [0, 1, 2, 3]
$ variables
$ makes variable global
Ie. $salary = 40000
hash = {}
Holds keys with values Ie. nums = { 'Dave' => '1234', 'Bill' => '2345' } nums['Dave'] => "1234" OR new way is Dave: 1234, Bill: 2345 Nums[:Dave] => 1234
Constants
Variable in all uppercase:
PI = 3.14
.to_s
Converts data to string
Ie. age = Integer(gets)
puts “Being “ + age.to_s + “ feels just like “ + (age-1).to_s + “!”
.rand
Randomizer Ie. nums = [] i = 0 while i < 5 nums[i] = .rand(101) i += 1 End
Parallel assignment
a, b = b, a
This will swap the values of the variables. Nice to use with data sorting w/o introducing new variable.
defined?
Defines data:
Ie. a = 1
defined? a
=> “local-variable”
.step
Use to “step” values. Ie. if step = 5, values will be incremented by 5.
0.step(15,5) {|i| print i, “ “ }
=> 0 5 10 15
case (when)
Useful "when" there's lots of data. Otherwise if/else statement is better. Ie: puts("Enter a grade: ") grade = gets grade = Integer(grade) case grade when 90..100 letterGrade = "A" when 80..89 letterGrade = "B" when 70..79 letterGrade = "C" when 60..69 letterGrade = "D" else letterGrade = "F" end puts("The letter grade is " + letterGrade)
break
use cautiously
Ends program if activated and/or will go to next line program after final end if there is one. Ie: if data/input == 0 then break end #next line
redo
Restarts program if activated. Ie: if data/input == 0 then redo end
next
Jumps to next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil).
for i in 0..5
if i < 2 then
next end puts "Value of local variable is #{i}" end
exit
Exits program. Ie: elsif tries == 3 puts "Sorry answer is apple." exit else puts "Try again."
require
Includes or “requires” the use of the named file:
require ‘./tempconvert’
puts ftoc(212) puts ctof(0)
rescue
Provides solution to an exception “error.” Ie. if you try and divide by zero.
Needs “begin”, “rescue” & “end”
begin print("Enter numerator: ") num = Integer(gets) print("Enter denominator: ") denom = Integer(gets) ratio = num / denom print(ratio) rescue print $! #this stores the exception puts print("Enter a denominator other than 0: ") denom = Integer(gets) ratio = num / denom print(ratio) end
Debug
(In terminal)
ruby -r debug file.rb
variable
storage location/s that hold data used by program
.slice
If passed a single index, returns a substring of one character at that index. If passed a start index and a length, returns a substring containing length characters starting at the index. If passed a range, its beginning and end are interpreted as offsets delimiting the substring to be returned. ie: a = "hello there" a[1] #=> "e" a[2, 3] #=> "llo" a[2..3] #=> "ll" a[-3, 2] #=> "er" a[/[aeiou](.)\1/, 0] #=> "ell" a[/(?[aeiou])(?[^aeiou])/, "non_vowel"] #=> "l"
.count
used to count characters. ie: a = "hello world" a.count "lo" #=> 5 a.count "lo", "o" #=> 2 "hello^world".count "\\^aeiou" #=> 4
c = “hello world\r\n”
c.count “\” #=> 2
.sub
substitutes ONLY the first occurrence of the pattern specified, whereas gsub is “global”. (see gsub card for examples)
.gsub
global substitution method. ie:
“hello”.gsub(/[aeiou]/, ‘’) #=> “hll”
“hello”.gsub(/([aeiou])/, ‘’) #=> “hll”
“hello”.gsub(/./) {|s| s.ord.to_s + ‘ ‘} #=> “104 101 108 108 111 “
“hello”.gsub(/(?[aeiou])/, ‘{\k}’) #=> “h{e}ll{o}”
‘hello’.gsub(/[eo]/, ‘e’ => 3, ‘o’ => ‘’) #=> “h3ll*”
“Super guper bag”.gsub “g”, “d” # => “Super duper bad”
“Ruby is 13%”.gsub( ‘%’ ) {|c| c.ord.to_s + ‘ ‘ } # => “Ruby is 1337”
.replace
Replaces the contents and taintedness of str with the corresponding values in other_str.
s = “hello” #=> “hello”
s.replace “world” #=> “world”
.scan (array or block)
Array:
a = “cruel world”
a.scan(/\w+/) #=> [“cruel”, “world”]
a.scan(/…/) #=> [“cru”, “el “, “wor”]
a.scan(/(…)/) #=> [[“cru”], [“el “], [“wor”]]
Block: a = "cruel world" a.scan(/\w+/) {|w| print "<> " } print "\n" => <> <> a.scan(/(.)(.)/) {|x,y| print y, x } print "\n" => rceu lowlr
.strip
strips whitespace. ie:
“ hello “.strip #=> “hello”
“\tgoodbye\r\n”.strip #=> “goodbye”
.floor
The .floor method rounds a float (a number with a decimal) down to the nearest integer.
.upto
iterates thru successive values, returning those values. ie:
3.upto(10) {|x| print x, “ “} => 3 4 5 6 7 8 9 10
“9”.upto(“11”).to_a #=> [“9”, “10”, “11”]
- ( *args) or splat argument
- tells Ruby that there could be more than 1 argument. ie:
#in this example *args takes 3 arguments:
def what_up(greeting, *args)
args.each { |bro| puts “#{greeting}, #{bro}?” }
end
what_up(“What up”, “Justin”, “Ben”, “Kevin”)
=> What up, Justin?
What up, Ben?
What up, Kevin?
proc (procedure)
http://ruby-doc.org/core-2.0/Proc.html
yield
used to "invoke" a block. useful for passing arguments within a method. ie: def double(number) yield(4) => 8 yield(8) => 16 yield(12) => 24 yield(number) => 12 end double(6) { |n| puts "#{n * 2}" }
:: (scope resolution operator)
Tells Ruby where to look for a specific bit of code. If we say Math::PI, Ruby knows to look inside the Math module to get that PI, not any other PI.
Domain
A domain is a field of study that defines a set of common requirements, terminology, and functionality for any software program constructed to solve a problem in the area of computer programming, known as domain engineering.
inject
Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator. # Same using a block and inject (1..3).inject { |sum, n| sum + n } #=> 6
# Same using a block (5..10).inject(1) { |product, n| product * n } #=> 151200
map
The map method can be used to create a new array based on the original array, but with the values modified by the supplied block:
arr = [1, 2, 3, 4, 5]
arr.map { |a| 2*a } #=> [2, 4, 6, 8, 10]
arr #=> [1, 2, 3, 4, 5]
#use of “!” is destructive
arr.map! { |a| a**2 } #=> [1, 4, 9, 16, 25]
arr #=> [1, 4, 9, 16, 25]
CRUD
Create, Retrieve, Update, Delete