Skip to main content

Posts

Showing posts from October, 2016

Specific Topic of Interest

Study Guide 120 - Object Oriented Programming classes and objects - classes is the template while object is the object created out of the template.  - class are focus on two things , states and behaviors. Object from the same class will have the same methods, same number of variables and variable names. However, the actual value of the variables will be different. These are object's states. using attr_* to automatically create setter and/or getter methods, and how to call them attr_accessor - create both a setter and getter of instance variable  attr_reader - create just a getter  attr_writer - create just a setter. - all attr* will create an instance variable for you, initialize to nil. - attr_accessor :name - this will create setter and getter for the instance var for @name . It will find the ivar with the same name. - when using setter method. Be sure to use "self.setter_method" syntax , if not , the computer think you are initializing a local va
var = /\A([aeiou]*)(.*)\z/.match("apple") This code regex will create an array with the first part is any length of vowel and the rest of the characters. var[0] = "apple" var[1] = "a" var[2] = "pple"

Creation of a new object occurs in the methods itself

Creation of a new object occurs in the non-mutating methods. Eg: Example 1 def fix(value)    value = value.upcase    value end s = "hello" t = fix(s) s = "hello" , object id : 100 t = "HELLO", object id : 200 Example 2 def fix(value)     value = value.upcase!     value end s = "hello" t = fix(s) s = "HELLO" , object id : 100 t = "HELLO", object id : 100

mutates the caller

String , Array , Hash, Range and customs objects can be mutated. That's why their object ID is different each time they are created. This is true even if their value is identical. Integers, Symbols, Boolean, NilClass can't be mutated. Their object ID is always the same.

each_slice(n)

each_slice will slice an enumerable object to a specific size without repeating [1,2,3,4].each_slice(2) do |chunk|     p   chunk end # [1,2] # [3,4] This is in contrast to each_cons. It will slice the enumerable to a specific size but with repeats. [1,2,3,4].each_cons(2) do |chunk|     p   chunk end # [1,2] # [2,3] # [3,4]

calling method from class methods

When calling another methods from class method , the method must be another class method. Why ? Because it doesn't make sense to call an instance method from a class method. What if there is no object instantiated. def self.classify(number)     raise RuntimeError if number <= 0     sum = sum_of_factors(number)     if sum == number       "perfect"     elsif sum > number       "abundant"     elsif sum < number       "deficient"     end   end     def self.sum_of_factors(number)     factors = (1...number).select { |n| number % n == 0 }     sum_of_factors = factors.reduce(:+)   end  

Reduce

(1..5).reduce do |sum, n|     sum + n if n.even? end This code will break. Why ? 1.when n = 1, the if statement is false. The whole statement returns nil. 2. nil returns to sum. 3. when n = 2 , sum + 2 means nil + 2 . Which will churn out an error.

Frequently Used Method - Hash

Hash 1. include? , has_key? It will return true if the object passed in match the KEY in the hash. eg: a = {:A => 200 , :B => 300} a.include?(200)  returns false a.has_key?(:A) return true 2. each { |key, value| } It will iterate through the hash key once. Returns the original full hash. eg: a = {:A => 200 , :B => 300} a.each do  |key, value|      puts key       puts value  end # A # 200 # B # 300 # return  {:A => 200 , :B => 300} 3. fetch It will return the value based on the hash key inputted eg: a = {:A => 200 , :B => 300} a.fetch(:A) # return  200 4. key It will return the key based on the value passed in. eg: a = {:A => 200 , :B => 300} a.key(200) # return :A

Scan

"hello world this is me !".scan(/\b[\w']+\b/) { |word| puts word } The above code will scan for a pattern of 1. word boundary 2. 1 or more word character plus ' 3. another word boundary Then it will output the word scanned. @phrase . downcase . scan ( /\w+'?\w+|\w+/ ) The above code will scan for a pattern of 1. one or more word character plus an ' (apostrophe) 2. the ? means the pattern to the left is one or none. In this case, whether ' is one or none. 3. follow by another word character of 1or more. 4. If the previous pattern didn't match , then use the second pattern. Which is 1 or more word character Word character is letters, numbers and underscore phrase . downcase . scan ( /[a-z]+'?[a-z]+|\d+/ ) The above code will scan for a pattern of 1. 1 or more any letters 2. 1 or none ' 3. follow by 1 or more any letters 4. If the previous pattern didn't match. 5. Then any length of digits.

What can Ruby do ?

I am trying to explain what can Ruby do essentially. I hope with this exercise, I am able to solve problem better because I know what can a programming language do at the basic level. Key data types 1. Strings 2. Numbers 3. Symbols 4. Nil 5. Boolean - true or false Key data structures 1. Arrays 2. Hashes 3. Range General Key Operations Comparison between two data type Ruby can compare between two data. 1. == comparison whether two data is equal. 2. >= large than 3. <= lower than 4. equals - compare whether two object are the same object (ie. pointing to the same data) Logic operation 1. && - logical AND that needs both to be TRUE before returning true. 2. || - logical OR that needs either one of them to be TRUE before returning true. Convert data types 1. convert Strings into Numbers (using #to_i) 2. convert Numbers into Strings (using #to_s) 3. All data types evaluates to TRUE except nil and false. 4. convert Arrays into Strings (using #joi

Regular Expression

These are the commonly used regular expression syntax. Basic Regex. 1. Input of literal will match whatever is inputted. It is case sensitive. For example /s/ will match all the 's' in cats , sands but will not match "S" in Superman. 2.   $ ^ * + ? . ( ) [ ] { } | \   The above are special characters , and must be escaped with a backslash. You can safely escape all special characters without errors. Spaces (" ") are not special characters , will be matched without backslash. 3.   /./ A period means any character. If you want to find "." only . Use backslash  /\./ 4. Regex will match any pattern you typed on it. If you typed /cat / it will match a "cat" followed by a space " " exactly. This is known as concatenation. The sequence of pattern matters. 5. If you want to choose one or the other,   /(cat|dog|rabbit)/   it will choose either cat , dog or rabbit. This is called Alternation. 6.  /launch/i If you want
The  Assignment Branch Condition size  warning is a complexity warning; your method is too complex. This is stated in convoluted language, but it's actually just a measurement of how many assignments, branches, and conditions you have in your method (a "branch" is a method call). To compute this metric, rubocop computes the number of assignments (call it  A ), the number of branches ( B ), and the number of conditions ( C ), then computes  Math.sqrt(A**2 + B**2 + C**2) . If the resulting value is greater than some size (18 by default), the method is said to exceed the Abc size, and rubocop complains. Fixing this is a matter of eliminating assignments, branches, and conditions from your method, either by simplifying the code, or by doing some sort of refactoring. Note that ruby tends to hide a lot of method calls (branches). For instance, if you have a getter defined in your class, every reference to that getter is a method call, even though it looks like a simple var

Equality

1. == test whether the value between two objects is the same. 2. equal test whether two objects are the same in ruby. (ie. whether they share the same object_id) 3. === test for equality in value , especially useful for Ranges. It is used implicitly in case statement 4. eql? is used in Hash to test whether the key and value are the same.