Skip to content

Instantly share code, notes, and snippets.

@kieetnvt
Last active September 11, 2018 01:51
Show Gist options
  • Save kieetnvt/2f56f83cd6e3cc570d992a7786dcc126 to your computer and use it in GitHub Desktop.
Save kieetnvt/2f56f83cd6e3cc570d992a7786dcc126 to your computer and use it in GitHub Desktop.
Lượm lặt từ Well grounded Rubyist

I. OJBECTS - METHOD CALL.

  1. dot operator and send method đều được dùng để gửi message đến 1 objec (yêu cầu object đó thực hiện message)
  2. 1 object cần quan tâm đến object_id, respond_to? và send
  3. nên kiểm tra respond_to?
if ticket.respond_to?(request)
  puts ticket.send(request) || ticket.request
else
  puts "no method request for ticket"
end
  1. phân biệt: send , __send__, public_send

__send__ là synonym của send ez. thường người ta dùng send nhưng lỡ có khi trong 1 số trường hợp cụ thể nào đó, dev định nghĩa lại 1 hàm send, nhưng vần muốn dùng 1 hàm send cũ thì __send__ sẽ được sử dụng.

send__send__ => có thể gọi các method private của object.

public_send => chỉ gọi được method public thôi.

  1. nói về method arguments của ruby:

ta cần phân biệt required args, optional args, arg defaul value và thứ tự các args trong Ruby. ví dụ:

def args_unleashed(a,b=1,*c,d,e)
  puts "Arguments:"
  p a,b,c,d,e
end

>> args_unleashed(1,2,3,4,5)
1
2
[3]
4
5
=> [1, 2, [3], 4, 5]
>> args_unleashed(1,2,3,4)
1
2
[]
3
4
=> [1, 2, [], 3, 4]
>> args_unleashed(1,2,3)
1
1
[]
2
3
=> [1, 1, [], 2, 3]
>> args_unleashed(1,2,3,4,5,6,7,8)
1
2
[3, 4, 5, 6]
7
8
=> [1, 2, [3, 4, 5, 6], 7, 8]
>> args_unleashed(1,2)
ArgumentError: wrong number of arguments (2 for 3+)
  1. phần khá quan trọng: variables, objects, and references:
  • References: biến ruby không giữ value mà chỉ reference đến 1 object value, ví dụ: str = "Hello" thì str không giữ giá trị "Hello" mà str sẽ tham chiếu tới string object (object vật lý chứa giá trị Hello trên RAM). abc = str => thì abc và str cùng trỏ đến cùng một string object. (mọi sự tác động làm thay đổi str cũng sẽ làm thay đổi luôn abc)

  • Exception: có 1 vài object chứa luôn giá trị mà không tham chiếu ví dụ: integer, symbol và 3 object đặc biệt: true, false, nil

  • Assigenment: bất kì thời điểm diễn ra việc Assignments => thì biến ruby được clear vùng nhớ trước đó , và thực hiện việc asignment mới.

  • L-values: left hand side value => không phải cái gì cũng có thể là left hand side value được hết. nó chỉ gồm: local variables, Class, global and instance variables.

  • Duping và Freezing object:

def change_string(str)
  str.replace("New string content!")
end
s = "Original string content!"
change_string(s)
puts s
=> "New string content!"

qua ví dụ trên, nếu bạn muốn bảo vệ giá trị ban đầu của argument thì method dup hoặc freeze

s = "Original string content!"
change_string(s.dup)
puts s
=> "Original string content!"
s = "Original string content!"
s.freeze
change_string(str)
puts s
=> "Original string content!"

dup vs clone: khá giống nhau về công năng , chỉ khác ở chỗ khi bạn dup 1 object frozen thì new object đó không bị frozen , ngược lại nếu clone thì tạo 1 new ọbect frozen

  • Bạn có thể change giá trị của 1 phần tử trong 1 Frozen aray!!
>> numbers = ["one", "two", "three"]
=> ["one", "two", "three"]
>> numbers.freeze
=> ["one", "two", "three"]
b
  >> numbers[2] = "four"
RuntimeError: can't modify frozen array
>> numbers[2].replace("four")
=> "four"
>> numbers
=> ["one", "two", "four"]

II. ORANGANIZING OBJECTS WITH CLASSES:

  1. Ruby dùng instance variables để nắm giữ trạng thái state của một object của một Class thông qua các hàm initialize, setter và getter method.

  2. Syntactic sugar là một thuật ngữ nói về những rules đặc biệt khi code, không như bình thường, nhưng mà lại dễ đọc dễ hiểu code hơn. Ruby hỗ trợ 1 số syntactic sugar như trong các setter methods. ví dụ: ticket.price= 63 và ticket.price = 63 thì price= 63price = 63 => là như nhau, đều gọi đến hàm def price=(value) => syntactic sugar cho phép bạn gọi methods call như là 1 phép gán assigenment.

  3. Setter methods unleashed: month, day, year = date.split('/')

  4. CREATING READER/WRITER ATTRIBUTES WITH ATTR_ACCESSOR attr_reader => getter methods attr_writer => setter methods attr_accessor => get + set methods. attr :name = attr_reader attr :name, true = attr_accessor

  5. Inheritance and the Ruby class hierarchy

  6. Single inheritance: one to a customer

  7. Trong cây quan hệ Inheritance => để check class object dùng is_a?(class parent or class ancestor) đều ra TRUE. Nó truy theo mối quan hệ (cây gia phả) => nếu nằm trong đường dây này thì đều ra TRUE

III. MODULES AND PROGRAM ORGANIZATION;

  1. The rules of method lookup summarized ■ Its class ■ Modules mixed into its class, in reverse order of inclusion ■ The class’s superclass ■ Modules mixed into the superclass, in reverse order of inclusion ■ Likewise, up to Object (and its mix-in Kernel) and BasicObject

  2. singleton method—a method defined directly on an object singleton method được lưu trữ trong 1 special class của object đó là the object’s singleton class

  3. Include lặp 1 module vào 1 class thì lần lặp Ruby xem như không có gì. (chỉ include 1 lần duy nhất trong 1 class)

  4. call super ở đâu thì lập tức nhảy về lớp Parent để gọi hàm tương ứng.

  5. Tôn trọng: the class Class is a subclass of the class Module Cat::Tom => Cat là module, Tom là class.

IV. THE DEFAULT OBJECT (SELF) - SCOPE - VISIBILITY:

  1. Keeping track of car manufacturing statistics with class variables
class Car
  @@makes = []
  @@cars = {}
  @@total_count = 0
  attr_reader :make

  def self.total_count
    @@total_count
  end

  def self.add_make(make)
    if !@@makes.include?(make)
      @@makes << make
      @@cars[make] = 0
    end
  end

  def initialize(make)
    if @@makes.include?(make)
      puts "Creating a new #{make}"
      @make = make
      @@cars[make] += 1
      @@total_count += 1
    else
      raise "No such make: #{make}"
    end
  end

  def make_mates
    @@cars[self.make]
  end
end
  1. CLASS VARIABLES AND THE CLASS HIERARCHY
  • Class Cha va Class con dung chung clss variables
  1. MAINTAINING PER-CLASS STATE WITH INSTANCE VARIABLES OF CLASS OBJECTS

  2. Deploying method-access rules: Private vs Protected methods

  • Both Private and Protected methods are not accessible from outside of the object as they are used internally to the object.

  • only way to call a Private method is to do so within the context of the object instance

  • Private method cannot be called with an explicit receiver, even if that receiver is itself.

  • Protected class method can be called within the context of an object of the same type.

  • This means you can call Protected class methods of other objects inside an object of the same type

V. WORKING WITH STRINGS:

puts "Backslashes (\\) have to be escaped in double quotes."
puts 'You can just type \ once in a single quoted string.'
puts "But whichever type of quotation mark you use..."
puts "...you have to escape its quotation symbol, such as \"."
puts 'That applies to \' in single-quoted strings too.'
puts 'Backslash-n just looks like \n between single quotes.'
puts "But it means newline\nin a double-quoted string."
puts 'Same with \t, which comes out as \t with single quotes...'
puts "...but inserts a tab character:\tinside double quotes."
puts "You can escape the backslash to get \\n and \\t with double quotes."

# the output
Backslashes (\) have to be escaped in double quotes.
You can just type \ once in a single quoted string.
But whichever type of quotation mark you use...
...you have to escape its quotation symbol, such as ".
That applies to ' in single-quoted strings too.
Backslash-n just looks like \n between single quotes.
But it means newline
in a double-quoted string.
Same with \t, which comes out as \t with single quotes...
...but inserts a tab character:
inside double quotes.
You can escape the backslash to get \n and \t with double quotes.
  • Other quoting mechanisms: %char{text}:

%q là '' %Q là ""

Ví dụ:

%q-A string-
%Q/Another string/
%[Yet another string]
[%q Hello! ]
[%q Hello\ there! ]
%q-Better escape the \- inside this string!-
%Q[I can put [] in here unescaped.]
%q(I have to escape \( if I use it alone in here.)
%Q(And the same goes for \).)
  • The 'HERE' doc with EOM - end of message:

Ví dụ:

>> text = <<-EOM
The EOM doesn't have to be flush left!
EOM
=> "The EOM doesn't have to be flush left!\n"
a = <<EOM.to_i * 10
5
EOM
puts a
Output: 50
array = [1,2,3, <<EOM, 4]
This is the here-doc!
It becomes array[3].
EOM
p array
The output is
[1, 2, 3, "This is the here-doc!\nIt becomes array[3].\n", 4]
  • ENCODING on top of the file:
# coding: UTF-8

puts __ENCODING__
=> #<Encoding:UTF-8>

VI. WORKING WITH SYMBOLS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment