Skip to main content

Reject, Select, is_a?, count, %w, regex

- Learnt EC2 basics from AWS and security groups
- Learnt .floor and .ceil
puts 2.67.ceil == 2 #=> false, because 2.67.ceil is 3
puts 2.67.floor == 2 #=> true, because true

- Learnt is_a?
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.


module M;    end
class A
  include M
end
class B < A; end
class C < B; end

b is an object of Class B and is A is the superclass of B. b will return true if B it belongs to class B or class A but not class C even if it is a subset of class B. It will return true if M is a module of class A or class B.

b = B.new
b.is_a? A          #=> true
b.is_a? B          #=> true
b.is_a? C          #=> false
b.is_a? M          #=> true

b.kind_of? A       #=> true
b.kind_of? B       #=> true
b.kind_of? C       #=> false
b.kind_of? M       #=> true

A class can only inherit from one class at a time (i.e. a class can inherit from a class that inherits from another class which inherits from another class, but a single class can not inherit from many classes at once).
http://rubylearning.com/satishtalim/ruby_inheritance.html

- There is something called a to_a? Complex 
- For more on complex, https://ruby-doc.org/core-1.9.3/Complex.html
- to_i rounds off the number to the first integer.
8.12.to_i => 8
8.77.to_i => 8

From friends.rb kata:
-Learnt .reject and .select
- Learnt more about regex. /i is case insensitive. So /^[a-z]{1,3}$/i means any case insensitive letter from 1 to 3. The $ sign needs to be behind.
- So /^[a-z]{3}$/i means exactly 3
- \s is whitespace
- This is the regex to find two specific words
(?=.*cat)(?=.*dog).*

for exact match use:

(?=.*\bcat\b)(?=.*\bdog\b).*

https://stackoverflow.com/questions/6437516/how-to-use-and-in-ruby-regex

- .reject can be used for array like:

(1..10).reject {|i|  i % 3 == 0 }   #=> [1, 2, 4, 5, 7, 8, 10]

# Remove nil & empty strings
{a: '', b: nil, c: 'third'}.reject { |k,v| v.nil? || v.empty? } # => {:c=>"third"}

- %w(a b v) is the same as [a, b, v]
%w{apple pear fig}.sort_by { |word| word.length}
              #=> ["fig", "pear", "apple"]

https://simpleror.wordpress.com/2009/03/15/q-q-w-w-x-r-s/

- .count
ary = [1, 2, 4, 2]
ary.count             #=> 4
ary.count(2)          #=> 2 as it finds only those values that are 2
ary.count{|x|x%2==0}  #=> 3. with a block, it compares which values can be divided by 2 and counts them.


Comments