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