try ruby Flashcards
reverse a string
.reverse
length of a string
.length
print string x times
”” * X
reverse number
1.to_s.reverse
to string
.to_s
to integer
to_i
to array
to_a
declare array / assign array
[] / x=[1,2,3]
[] creates an empty what
list
does a list store thing out of order
false
get max from array
.max
sort array
.sort!
method with ! does what
changes value for good
replace all string x in an array containing x
arr[‘x’]=’y’
reverse an array with a string of lines, (only each individual line) without writing words backwards
poem.lines.to_a.reverse
join elements in an array
.join
check to see if something is included
.include?
lowercase everything
.downcase
delete an obj
.delete
dictionary or hash
books={}
add elements to a dictionary/hash
books[“title”] = :splendid
can you use length on a dictionary/hash?
yes, will return number of items within
iterate through a dictionary/hash’s values
books.values.each{|rate| ratings[rate]}
iterate and count number of times rate appears through a dictionary/hash’s values
books.values.each{|rate| ratings[rate]+=1}
returns like {:good=>2, :bad:=>5}
how do you create a block in ruby
curly braces
a way of performing something x times
5.times {print “hi! “}
how to create a symbol
:symbolhere
blocks
chunk of code which can be tacked oon to many of rubys methods
access directory
Dir.entries “/” (anything listed after a method is called an attatchment, like the / in this example)
Dir[] does what
searches for files with wildcard characters
read a file
File.read()
copy a file to new dir
FileUtils.cp(‘file1’, ‘destination’)
open file
File.open()
using the pipe character in a do statement
File.open(“txt.txt”, “a”) do |f|
f«_space;“Cat”
end
check when a file was changed
File.mtime(filename.txt)
can also append .hour to it to just get hour
how are arguments seperated in ruby
commas
define a method in ruby
def methodname
code
end
split
method for strings, breaking it into an array based on the given char to split on
strip
removes extra whitespace around the url
p line is short for what
paragraph
create a list
list do
p”1”
p “2”
end
to load a library
require ‘library’
the .new method does what
used to make objects of a certain class
define a class
class Nameofclass
How to instantiate a class
x=NAmeofclass.new
what is attr_accessor
attributes or variables attatched to the class, used for acccesing outside the class
how to declare an instance variable
@x
what are instance variables
vars for accesing inside the class
sort attributes with a time association in ascending order
blog.sort_by { |entry| entry.time }.reverse
add new entries
«_space;x
what can the map method do
cycle through an array and replace each item with something new
Time method
Time.now
Time.now-2.weeks
use a variable in a string
“Hello #{variable}”
execute a block of code x times
x.times do
code
end
iterate through an array
array.each do |n|
puts n
end
unless
evaluates to if not, do
an if, else if, else statement in ruby
if x==0 puts x elsif x==1 puts x else puts x end
.empty?
boolean for if something is empty
nil is treated as what in ruby
false
path of a file method
.file_path
empty strings, 0, and empty arrays are treated as what
true
fail raises what kind of error if true
runtimeerror
written fail “wrong password”
will raise exception wrong password
what hapens in result= 1||2
returns 1, because it doesnt need to evaluate the second half
create an array using ||
tweets=timeline.tweets||[]
if tweets returns nil, it creates an array otherwise it assigns them
does every method in ruby return a value
yes
case statements in ruby
case, when, then, else, end
use grep method in ruby
search = "Super Mario Bros." games = ["Super Mario Bros.", "Contra", "Metroid", "Mega Man 2"] matched_games = games.grep(Regexp.new(search))
uppercase all letters
.upcase on stringleas
are variables an object
kind of, its a reference to an object (east previous to ruby 2)
ruby convention for naming variable
underscores betweeen words
class variable indicator
@@
instance variable indicator
@
exponential operator
**
find class type of something
.class
what operator appends an item to an array
«
ruby is inspired by
perl, smalltalk, eiffel, ada
ruby is a blank language
dynamic
when ruby runs, it is translated and executed how
on the fly
what is the standard ruby interpreter
MRI (alternative:rubinius amd jruby, whihc runs on java vm)
to run ruby what do you need
a ruby interpreter
in ruby what is repl
read evaluate print loop
in ruby what is the => operator called
hash rocket
in ruby 1.9.3 how many reserved words are there
40
what are the 4 types of variables in ruby 1.9.3
local, global, instance, constant
in ruby how do you define a global variable
$– can be cap or lowercase
in ruby how do you define a constant var
all upercase
in ruby how do you define a instance variable
@
in ruby what is the difference bw an instance variable and a local
instance variables are accesible throughout the class
in ruby an class typically uses what case struct
camel, upper first too
how to define a case statement in ruby
case
when x
in ruby, def initialize is like what
a constructor
in ruby how can you output the value of a variable from within a sting
using the#{var} // this is called interpolation– if wrapped in single quotes, this will not work
in ruby how do we get input from the user
the gets method
inrubywhat does chomp do
removes whitespace
3 ways to create a string in ruby
String.new(), single quotes, double quotes
in ruby when using single quotes, do you need an escape for example a double quote?
no
what are 3 concatination operators for strings in ruby
«_space;and + and .concat
if using the [n] on a string like name[0] what does it return
the ascii representaton of that letter
in ruby what is the method for removing trailing whitespace
.chop
how to find the index of a letter in a string ruby
.index(“x”)
in ruby how do you find how many letters are in the string
.length or .size
in ruby how do you find what is swapcase
swaps upper for lower and vice versa
in ruby what does split do
returns an array split on the given value .split(“ “)
runnin g .size in ruby on a fixnum (i) what is returned
the bytes it takes up
in ruby what is a combined operator comparison symbol and what does it return
0 if equal 1 is lef is greater -1 if right is greater
in ruby the .eql? does what
checks if the value AND type are the same
how to access values in a library
libname::x
how to generate a random number in ruby
rand (addditonally you can use a follow number to find rand between 0->x)
to use a library in ruby what do you do
require “lib”
in ruby bigdecimal fixes what
the floating point math problem
in ruby how to use make a floating umber to bigdecimal
BigDecimal.new(x)
in ruby [1,2,3]&[2,3] wpold return what
[1]
in ruby how to put values at the beginning of an array
unshift(x)
how to clear an array in ruby
.clear
in ruby how to flatten a multi-d array
.flatten!
what does array.select do with a given block, what about reject and any and all
returns values iwthin the array that are validaated as true. i.e array.select {|item| item>x}
alternatively you can use reject to basically perform a !=
any? and all? return booleans – selef explanatory on when it would return t/f
in a ruby hash how can you find a single element, what about all elements that match? You can allso use .all
hash. find{|key,value| key==’x’} //returns array
hash. find_all{|key,value| value.match(‘x’)} //returns array
You can allso use .all? and any for their boolena return
how to find how many values are in a has
.any method
how to convert a hash to an array
hash.map{| key, value| value =”(hash) #{value}”} //returns an array with the hash in parenthesis prepended to the value [“(hash) value”, “(hash) value2)”]
do ruby methods accept default values
yes
in ruby how do you create a class method
prefix it with the word self //self.method
in ruby what does ||= do
this is a conditional assignment operator– for example it checks if it exists, and if it doesnt, then it does
in ruby what is the way to set a set and get method
attr_reader/writer :x
or
attr_accesor
what s=is an alternate way of creating a group of class methods without using self on each method
class << self def method end def method2 end end
in ruby how do you make a private method
define the method normally, and then use private :method at the end, or you can use the word private above all private methods
in ruby methods have what protection level by default
public
in ruby how can a class call its own private method
creating a new public method that has the private method nested within the body
def call_private
private_method
end
in ruby what is a protected method
protected methods can be called within the class and by other objects/subclasses
in ruby how do you write a forloop
for i in array do
x
end
in ruby what is the keyword that skips to the next iterationn oif the loop
next
in ruby what is the keyword that breaks out of a loop entireley
break
how can you run a loop until a certain value is gotten without using the until loop
loop do combined with break
in ruby what does retry do? what about redo
retry reexecutes the entire loop, redo will only redo the current iteration it is on until end
In ruby how do we pass a block into a method
method(&blockname)
in ruby how do you create a block
curly braces, or do and end (curly braces have a higher priority
in ruby how do you call a block
the call method
in ruby what is the method to check if a block was passed to a method
block_given?
in ruby what is the keyword to make sure something is given (in error checking)
ensure
in ruby how do you raise an error
using the raise keyword followed by an error
in ruby if an error is expcted what can we use to counter it
using the rescue statement
in ruby what do BEGIN and END blocks do
BEGIN is run at the beginning of a program, end is run at the end of a program
in ruby what does yield do
The yield statement gives control of the current method over to the block that is passed in. Yield can also be used to send a variable value in to, or out of, a block of code
in ruby how do you create a proc
proc.new with a block
Proc.new{block here}
or you can use lower case proc with block assigned to a variable
in ruby how do you create a lambda
similar to proc, you assign a variable to lambda { block here}
you can also use the skinny arrow ->{ block }
in ruby how does a proc take an argument
using the pipes. mproc= proc {|passedin| }
in ruby what is the major difference between a proc and a lambda
lamdas require the exact number of arguments specified, also a specified return in a proc prior to the final line will return that, whereas a lamda will return the final return value
in ruby how do you write multi line comments
=begin
=end
in ruby what does capitalize do
capitalizes the first lettter
in ruby what is the naming convention and keyword to create a new module
module in camelcase (first upper too)
in ruby, what naming convention do you use to create a constant
all uppercase
In ruby (specifically irb) what symbols do you use to access something from within a loaded module
::
in ruby modules are primarily used to accomplish what
namespacing
in ruby what does extending allow us to do in terms of modules and classes
using .extend, a class can access a modules internals
in ruby, alternative to using extend to access methods inside a module, what can we do
include the module inside the class
what is the main difference between a symbol and string in ruby
a symbol only exists once in memory for a session
in ruby how can we override default methods for instance to_S
within a classs, you can create a to_s method