Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Explicit Casting vs. Implicit Coercion Trong Ruby: #to_s vs. #to_str Giải Thích

Type coercion là việc thay đổi type của object sang type khác, cùng với value của nó. Ví dụ, thay đổi Integer thành String với #to_s hoặc Float thành Integer với #to_i. Các methods ít known hơn #to_str và #to_int mà một số objects implement làm giống nhau at first glance, nhưng có differences.

Trong edition này của AppSignal Academy, chúng ta sẽ dive vào explicitly casting và implicitly coercing types trong Ruby, while briefly touching on typecasting actors. Chúng ta sẽ cover differences giữa cả hai methods, và discuss cách chúng được dùng.

Hãy first look at cách chúng ta usually coerce values sang different types trong Ruby với explicit casting helpers.

Explicit Casting Helpers (Helpers Ép Kiểu Tường Minh)

Common casting helpers nhất là #to_s, #to_i, #to_a và #to_h. Đây là explicit casting methods. Chúng giúp chúng ta dễ dàng transform value từ type này sang type khác.

Explicit helpers đi kèm clear promise. Bất cứ khi nào #to_s được gọi trên object, nó luôn luôn return string, ngay cả khi object không really convert to string well. Giống như casting Michael Keaton làm Batman. Bạn sẽ get a batman, ngay cả khi comedy actor không especially suited cho role.

Ruby cung cấp helper methods này trên hầu hết basic objects trong Ruby standard library.

1.to_s        # => "1"
1.to_i        # => 1
[1, 2].to_a   # => [1, 2]
{ a: 1 }.to_h # => { a: 1 }

Các methods này, đặc biệt #to_s, được implement trên hầu hết basic types trong Ruby. Mặc dù casting hầu như luôn return value, result có thể không phải những gì chúng ta expect.

Object.new.to_s  # => "#"
nil.to_s         # => ""
nil.to_i         # => 0
nil.to_a         # => []
nil.to_h         # => {}

Gọi #to_s, #to_i, #to_a và #to_h helpers forces bất kỳ value nào sang selected type. Chúng return representation của type bị coerce tới regardless of what happens to the value.

Implicit Coercion Methods (Phương Thức Ép Kiểu Ngầm)

Gọi type casting methods trên values không act như type chúng ta cast to có thể gây errors hoặc loss of data. Ruby cũng cung cấp implicit coercion methods chỉ return value khi objects act như type đó. Cách này chúng ta chắc chắn value act như type chúng ta muốn. Implicit coercion methods là #to_str, #to_int, #to_ary và #to_hash.

Implicit coercion giống như casting Leonard Nimoy vào bất kỳ role nào trừ Spock. Sẽ work nếu character đủ close to Spock, nhưng fail nếu không. Helper #to_str cố gắng convert to string, nhưng sẽ raise NoMethodError nếu object không implement method và không thể implicitly coerced.

"hello".to_str  # => "hello"
123.to_str      # => NoMethodError (undefined method `to_str' for 123:Integer)

Chúng ta thấy Ruby strict hơn về gì được và không được coerce sang requested types. Nếu coercion không possible, method #to_* không implemented trên object và gọi nó raise NoMethodError.

Khi dùng implicit coercions, ví dụ #to_str, chúng ta ask function return String object, chỉ nếu original type cũng act như String. Vì lý do này, #to_str chỉ implemented trên String trong Ruby Standard Library.

Cách Ruby Sử Dụng Implicit Coercion

Ngoài việc precise hơn trong việc ask during coercion, implicit coercion useful cho gì nữa? Tiếng ra Ruby dùng implicit coercions itself trong quite a bit scenarios. Ví dụ, khi combine objects với +.

class Name
  def initialize(first, last)
    @first, @last = first, last
  end
end

name = Name.new("John", "Doe")
"Hello " + name
# => TypeError (no implicit conversion of Name into String)

Ở đây, Ruby raise TypeError vì không thể implicit conversion từ type Name sang String.

Nếu implement #to_str trên class, Ruby biết cách coerce type Name.

class Name
  def initialize(first, last)
    @first, @last = first, last
  end

  def to_str
    "#{@first} #{@last}"
  end
end

name = Name.new("John", "Doe")
"Hello " + name  # => "Hello John Doe"

Cùng works cho Arrays và #to_ary.

class MyArray
  def to_ary
    [1, 2, 3]
  end
end

arr = MyArray.new
[0, *arr]  # => [0, 1, 2, 3]

Nhưng #to_ary dùng trong more scenarios. Chúng ta có thể dùng nó để destructure Array thành separate variables.

class Coordinates
  def to_ary
    [10, 20]
  end
end

x, y = Coordinates.new
# x = 10, y = 20

Nó cũng làm conversion của object thành block parameters.

class Pair
  def to_ary
    [1, 2]
  end
end

Pair.new { |a, b| a + b }  # => 3

Có more scenarios nơi implicit coercion methods được dùng, như #to_hash với **. Nó coerce value thành hash với #to_hash trước khi pass to parse_options method.

class Options
  def to_hash
    { foo: :bar }
  end
end

def parse_options(**opts)
  opts
end

parse_options(**Options.new)  # => { foo: :bar }

Enforcing Types (Buộc Kiểu)

Ruby cũng cung cấp resilient coercion methods hơn khi type unknown và chúng ta want to make sure get correct type. Có one cho every basic type (String(...), Integer(...), Float(...), Array(...), Hash(...), etc.).

String(123)       # => "123"
Integer("123")    # => 123
Float("1.5")      # => 1.5
Array(1..3)       # => [1, 2, 3]
Hash(a: 1, b: 2)  # => { a: 1, b: 2 }

Method String(...) first tries gọi #to_str trên value, và khi fail, gọi #to_s method. Không phải all objects define #to_str method, do đó checking với both implicit coercion (#to_str) và explicit (#to_s) casting methods tăng chances String conversion sẽ work và bạn get value you want. Bằng cách first call implicit coercion, chúng ta more likely get result có same value nhưng của coerced type, không phải như "#<Object:0x00007f8e6d053a90>".

class Weird
  def to_str
    "from to_str"
  end

  def to_s
    "from to_s"
  end
end

String(Weird.new)  # => "from to_str"

Bạn should only implement implicit casting methods cho objects act như to be coerced type, ví dụ #to_str cho own String class.

Ngoài first try implicit coercion, helper String(...) cũng check returned type. #to_str chỉ là method có thể return bất kỳ type value nào, even non-Strings. Để ensure get value of requested type, String(...) raise TypeError nếu types don't match.

class BadToStr
  def to_str
    nil
  end

  def to_s
    "fallback"
  end
end

String(BadToStr.new)  # => "fallback" (ignores nil from to_str, falls back to to_s)

Ở đây, Ruby ignores result của #to_str vì nó return nil, không phải String-type. Thay vào đó, fall back to #to_s result.

Nếu #to_s cũng return nil và thus không đúng type, String(...) sẽ raise TypeError.

class BadBoth
  def to_str; nil; end
  def to_s; nil; end
end

String(BadBoth.new)  # => TypeError (can't convert BadBoth to String)

Mặc dù chúng có thể reliable hơn enforcing type coercion, lưu ý casting helper methods (String(...), Integer(...), etc.) usually slower vì cần perform more checks trên given value.

Kết Luận

Khi bạn want to make sure dealing with right type of data cho object, type coercion là useful process. Trong bài này, chúng ta refreshed knowledge của explicit casting helpers như #to_s, #to_i, #to_a và #to_h. Chúng ta cũng looked at instances khi implicit helpers như #to_str, #to_int, #to_ary và #to_hash useful và cách Ruby itself dùng chúng.

Chúng ta hy vọng bạn found this type coercion overview useful và how you found the actor typecasting analogy. As always, let us know nếu có topic bạn muốn chúng ta cover. Nếu có questions hoặc comments, đừng ngần ngại drop us a line @AppSignal.

Explicit Casting vs. Implicit Coercion Trong Ruby: #to_s vs. #to_str Giải Thích

Tom de Bruijn