General Flashcards
Name all the 19 Parts of Speech of the Ruby language.
Variables, Global Variables, Instance Variables, Class Variables, Constants, Symbols, Methods, Class Methods, Method Arguments, Numbers, Strings, Blocks, Block Arguments, Ranges, Arrays, Hashes, Regular Expressions, Operators, Keywords,
Any plain, lowercase word.
Variable
Variables can consist of what types of characters?
letters, digits and underscores
What are these examples of? x, y, banana2, phone_a_quail
Variables
Two types of Numbers
Integers and Floats
A series of digits which can start with a plus of minus sign
Integer
What are these examples of? 1, 23, -1000, 12_000
Integer
Numbers with a decimal point or scientific notation
Float
What are these examples of? 3.14, -8,08, 12.043e-04
Float
Any sort of characters surrounded by double or single quotes
String
What are these examples of? “sealab”, ‘2021’, “These cartoons are hilarious”
String
Look like variables, but start with a colon
Symbol
What are these examples of? :a, :b, :ponce_de_leon
Symbol
Looks like variables, but capitalized
Constants
What are these examples of? Time, Array, Bunny_Lake_Is_Missing, EmpireStateBuilding
Constant
Verbs attached to variables and constants by a dot
Method
Provides additional information to a Method to perform more specific actions
Method Argument
What are these examples of? front_door. open
variable.method
What are these examples of? front_door.paint( 3, :red)
variable.method.method argument
Usually attached after a variable and/or constant with a double colon
Class Method
What are these examples of? Door::new( :oak)
Constant::class method (method argument)
Variables that start with a dollar sign
Global Variable
What are these examples of? $1, $x, $chunky
Global Variable
Variables that begin with @ symbol often used to define the attributes of something
Instance Variable
What are these examples of? @x, @y,
Instance Variable
Variables that begin with a double @@ used to define attributes to many related objects
Class Variable
What are these examples of? @@x, @@y
Class Variable
Characters surrounded by curly braces to group a set of instructions together so that they can be passed around
Block
A set of variables surrounded by pipe characters and separated by commas
Block Argument
Two values surrounded by parantheses and separated by an ellipsis…two or three dots
Range
What are these examples of? (1..3)
Range
A list surrounded by square brackets and separated by commas
Array
What are these examples of? [1,2,3]
Array
A dictionary surrounded by curly braces. Dictionaries match words with their definitions. Ruby does so with arrows made from an equal sign followed by a greater than sign
Hash
What are these examples of? {‘a’ => ‘aardvark’}
Hash
A set of characters surrounded by slashes used to find words or patterns in text
Regular Expression
What are these examples of? /ruby
Regular Expression
Characters used to do math to compare things
Operator
Built in words, imbued with meaning that cannot be used as variables of changed
Keywords
How to print to screen?
“puts “
“p “
How to output to screen without newline?
How to evaluate variable inside double quotes?
“test #{ variable}”
How to open and close a file?
aFile = File.new(“filename”, “mode”)
process_the_file
aFile.close
How to read the first 20 characters in a file?
sysread can be used to read the contents of a file
e.g. content = aFile.sysread(20)
how to read the lines of a textfile?
arr = IO.readlines(“fileltest.txt”)
How to read lines with Ruby?
File.open(‘test.txt’).each_line{ |s| puts s }
or
File.foreach(‘test.txt’) { |s| puts s }
What is the output?def callBlock yield yieldendcallBlock { puts In the block” }”
In the block
In the block
What does this produce?a = %w( ant bee cat dog elk )a.each { |animal| puts animal }
ant bee cat dog elk
What is the effect of this?a = %w{ ant bee cat dog elk }
an array of string with values
e.g.
a[0]»_space; “ant”
a[3]»_space; “dog”
How do you define a hash/dictionary?
instSection = { 'cello' => 'string', 'clarinet' => 'woodwind', 'drum' => 'percussion', 'oboe' => 'woodwind', 'trumpet' => 'brass', 'violin' => 'string' }
Give an example of simple iteration over array
[1,2,3].each do | value |
puts value
end
Give different ways to create an array with values: vitamins, minerals and chocolates
# Make a list of clues for a game of charades clues = ['vitamins', 'minerals', 'chocolates']
# Create the same array by splitting on whitespace clues = %w(vitamins minerals chocolates)
# Create the same array in steps clues = Array.new clues << 'vitamins' clues << 'minerals' clues << 'chocolates'
How can you pass arguments to a block?
using | arg | in the start of the block
how to match line with regex?
if line =~ /Perl|Python/
puts Scripting language mentioned: #{line}”
end
how to control flow with if/else in ruby?
if customerName == "Fred" print "Hello Fred!" elsif customerName == "John" print "Hello John!" elsif customername == "Robert" print "Hello Bob!" end
how to access substrings?
string = this is an example”
=> “this is an example”
value = string[2..6]
=> “is is”
string[11..-1] = “elephant”
string
=> “this is an elephant”
how can you iterate from 0 to 10
(1..10).to_a.each do |n|
…
end
Meta programming:How to access meta information of a class?
instance_variable_get ‘@event’
instance_variable_set ‘@region’, ‘UK’
instance_variables5.public_methods
How to create instance variables with introspection?
class Person def initiliaze(attributes) attributes.each do | attr, value | instance_variable_set("@#{attr}", val) end end end
Person.new :name => ‘Peter’, :age => ‘31’, :sex => :male
why are instance variables marked with @ ?
with the mark @ with can identify variables as instance variables and do not need getters and setters
What is the convention for using ‘?’ as part of method names?
Conventional in Ruby to have ‘?’ at the end of the method if that method returns only boolean values
What does ‘@’ signify if it’s part of the variable name?
Instance variable
What is a lambda?
lambda is just a function… peculiarly… without a name. They’re anonymous, little functional spies sneaking into the rest of your code. Lambdas in Ruby are also objects, just like everything else!
Convention is to use {} for single line lambdas and do..end for lambdas that are longer than a single line.
Lambdas vs. Blocks
A lambda is a piece of code that you can store in a variable, and is an object. The simplest explanation for a block is that it is a piece of code that can’t be stored in a variable and isn’t an object. It is, as a consequence, significantly faster than a lambda, but not as versatile and also one of the rare instances where Ruby’s “everything is an object” rule is broken.
most common uses for a lambda
one of the most common uses for a lambda involves passing exactly one block to a method which in turn uses it to get some work done. You’ll see this all over the place in Ruby - Array iteration is an excellent example.
module
Modules only hold behaviour, unlike classes, which hold both behaviour and state.
Since a module cannot be instantiated, there is no way for its methods to be called directly. Instead, it should be included in another class, which makes its methods available for use in instances of that class.
What is ‘::’ ?
:: is a constant lookup operator that looks up the Array constant only in the Perimeter module.
symbol, ex :octocat
Immutable string whose value is itself, typically used for enumeration. its own primitive type.
Used in Ruby to denote “specialness” such as being one of the set of fixed choices like an enumeration. Symbols can easily be converted back and forth with the methods to_s and to_sym.
Return value of ‘puts’ versus ‘return’
always nil versus sum
1+1 returns 2
primitives versus objects
Primitives dont have a common relationship to each other
variables
Will always be undefined or ACT like an object
They are not objects
variable scope indicators
Global $variable Class @@variable Instance @variable Local variable Block variable
array
An array is an ordered integer- indexed collection of objects.
That’s a very fancy way of saying that we can take objects and put them together in order, and keep their position in the same order, and we can refer to those objects by their positions.
Expanding file folder is good analogy because folders can be empty. Classes can be put in arrays.
a.b means: ____ ____ b on ______ a
•a.b means: call method b on object a
•a is the receiver to which you send the method call,
assuming a will respond to that method
•does not mean: b is an instance variable of a
•does not mean: a is some kind of data structure
that has b as a member
def by_three?
best practice to end methods with a question mark if they return a boolean in ruby
blocks
create a method with no name. Blocks can be defined with either the keywords do and end or with curly braces ({}).
is 0 true of false
0 or empty string is true. False and nil are the only things that are true. They are not the same thing but they both return false
what is returned by default from a method?
- if a method does not explicitly return a value, the last expression’s value is returned, ex
poetry mode
omit paretheses around arguments to a method call, and omit curly braces when LAST argument to a method call is a hash
there’s a single hash argument, and its the last argument
Describe polymorphic associations
Allow you to have a single model that can be associated to an arbitrary number of other models.
Person, Company, Address
What are nested resources?
They are the touted as the correct way to do REST with parent child model associations.
- Set up named route
map. resources :events, :has_many => :tickets - Route helpers
new_event_ticket - before_filter :get_event
def get_event @event = Event.find(params[:event_id]) end
Migration
At the most basic level Migrations allow you to define incremental changes to your data model (and data itself!). This sort of approach melds seamlessly with Agile and XP methodologies favored by Rails developers the world over. A Migration is defined by subclassing ActiveRecord::Migration and overriding the two required method definitions, self.up and self.down:
class SampleMigration < ActiveRecord::Migration def self.up end
def self.down
end
end
Within the up and down definitions you can create tables and indexes, add data, manipulate models and more.