Ruby
- Ruby and Scalability
- If github, airbnb and hulu can use it successfully, so can you.
- Hulu is handling almost 10M unique visitors per month
- Great for developer productivity and happiness
- Implementations
- MRI, YARV, Jruby, Rubinius
- Jruby and Rubinius have better thread support
- Features
- Duck Typing - An object’s type is determined by its data and methods
- Open Classes
- Meta Programming - Modify classes and methods at runtime
- Inheritance - Does not support multiple inheritance, but provides modules and mixins
- Multiple paradigms - supports multiple paradigms like oop and functional
- Automated memory management (garbage collection)
- Modules
- Modules have 3 main usecases
- Namespacing
include
If you have methods that could be used in several classes, extract them to a module and include it in the classes. Each object has access to those methods. Modules may have requirements about what attributes are defined in the classextend
Instead of the entire class, if we want only a particular object to have access to the module’s functionality we can saymy_obj.extend my_module
- Executing Ruby Code
ruby main_file.rb
- on terminalcmd + B
- on sublime text
- String vs Symbol
- Symbols are immutable
- Require
require awesome
- File extension is not required
- Works with absolute and relative paths
- Loads the file only the first time it is encountered
- Load
load amazing.rb
- File extension is required
- Works with absolute and relative paths
- Loads the file every single time it encounters the statement
- Does not check if the file is already loaded
- Good for exploratory code loading
- Make changes to the file and load them again in a single session
- Include
- Modules and reusable code
- Extend
- For class methods
- Block
- Blocks are inspired by functional programming language Lisp. Functional programming languages encapsulate functions insdie variables, which could then be passed around and executed when needed.
- Blocks can have 2 notiations - Piece of code enclosed between { } or do end. Hash has curly braces too, but only encloses key-value pairs.
- Passed as parameter to methods, which can then execute the block anytime using the
yield
keyword -
Blocks can take parameters 1 for array and 2 for hash passed between the characters
- Proc
- Procs & lambdas are ruby blocks. Instead of declaring them anonymously, we assign a proc to a variable
- Variable can then be passed to a method
- Lambda
- Lambda differs from the proc by requiring all the arguments to be passed correctly
- Used to define scopes in rails models
- Range
..
- both inclusive...
- last element excluded
- Variable Arguments
- ``` def compute_result(*param) # Do something end
compute_result(1,2,3,4) ```
- Exceptions
- Exceptions are ruby classes
ZeroDivisionError
NameError
- when you call a method that is not definedArgumentError
raise
begin
rescue
- stop the errors from crashing the program. Enclosed in a begin-end blockend
ensure
- Rest of the code could not be executed
catch
throw
- break
- Terminates the innermost
-
&:
Operator - Meta Programming
- Not all languages have meta programming capabilities. Example: C
- Java is catching up
- Code that writes code
- Manipulate elements in runtime. Dynamically create classes, methods and variables
ActiveRecord
makes heavy use of metaprogramming. Dynamic Finders likefind_by_title
do not actually exist in the codebase.- Most classes are inherited from
BasicObject
Object
orKernel
. Use theancestors
method - Define
method_missing
``` def method_missing method_name, *args, &block
end ``` *
Math.const_get(:pi)
- module method. Gets the value of the constant or a name error *Math.const_set(:pi, 3.14)
- module method. Sets the value of the constant *k.send(:hello, "Warm", "Welcome")
- class method. invokes the method identified by the symbol and passes it any arguments * Defining classes in runtime * Classes can be assigned to a variable * add self in the class * You can have logic inside of classe - Struct
Struct
- bundles a group of variables- Can be used as Light weight classes
- Inherits from the Enumerable
- Structs can be used to pre determine the attributes of a class
- Set
Set
is like an array, but enforces uniqueness- Responds to intersection, difference, merge etc
- Hash -Freq Used Methods
h1 = Hash.new
h1 = {}
h1["author"]="matz"
h1[:title]="ruby"
h1.keys
h1.values
h1.delete(k)
h1.has_key?(k)
h1.has_value?(k)
h1.flatten
- converts hash to an arrayh1.to_a
- converts each pair into an arrayh1.invert
- reverts k & vh1.reject{|k,v| k <5}
-h1.each{|k,v| v*10}
- Enumerable Methods
Enumerable
module provides collection classes with several traversal, search and sort methods- The class much provide an
each
method which yields successive members of the collection - If
max
min
orsort
methods are to be used, then the collection must also implement a<=>
method all?
any?
none?
one?
map
each_with_index
select
inject
reduce
-
Categories
-
Database
-
Programming
-
Workflow
-
Devops
-
Architecture
-
Ui
-
Frameworks
-
Blogging