Type Coercion คือการเปลี่ยน Type ของ Object เป็น Type อื่น พร้อมกับ Value เช่น เปลี่ยน Integer เป็น String ด้วย #to_s หรือ Float เป็น Integer ด้วย #to_i Method เลือกน้อยที่รู้ #to_str และ #to_int ที่บาง Objects Implement ทำ Same At First Glance แตมี Differences
ใน AppSignal Academy Edition นี้ เราจะ Dive Into Explicitly Casting และ Implicitly Coercing Types ใน Ruby พร้อม Briefly Touch on Typecasting Actors เราจะ Cover Differences Both Methods และ Discuss How They're Used
มาดูก่อนว่าเรา Coerce Values to Different Types ใน Ruby กับ Explicit Casting Helpers ยังไง
Explicit Casting Helpers
Common Casting Helpers คือ #to_s, #to_i, #to_a และ #to_h นี่คือ Explicit Casting Methods ช่วย Transform Value จาก Type หนึ่งไปอีก Type ได้ง่าย
Explicit Helpers มาพร้อม Clear Promise ทุกครั้ง #to_s Called on Object มัน Always Return String แม้ Object ไม่ Really Convert to String Well มันเหมือน Casting Michael Keaton as Batman You'll Get Batman แม้ Comedy Actor ไม่ Suited สำหรับ Role
Ruby Offer Helper Methods นี้บน Almost Any Basic Object in Ruby Standard Library
Methods นี้ โดยเฉพาะ #to_s Implemented on Most Basic Types in Ruby แต Casting Almost Always Returns Value Result อาจไม่ใช่ที่ Expect
Calling #to_s, #to_i, #to_a และ #to_h Helpers Forces Any Value to Selected Type Return Representation of Type Coerced To Regardless What Happens to Value
Implicit Coercion Methods
Calling Type Casting Methods on Values ที่ Do Not Act Like Type We Are Casting To Can Cause Errors หรือ Loss of Data Ruby Also Offers Implicit Coercion Methods Which Only Return Value When Objects Act Like Type นี้ Way We Can Be Sure Value Acts Like Type We Want Implicit Coercion Methods คือ #to_str, #to_int, #to_ary และ #to_hash
Implicit Coercion เหมือน Casting Leonard Nimoy as Any Role but Spock They'll Work If Character Close Enough to Spock But Fail If Not #to_str Helper Tries Convert to String But Raise NoMethodError If Object Doesn't Implement Method และ Can't Be Implicitly Coerced
เราเห็น Ruby Stricter ตอนนี้ What It Does/Doesn't Coerce to Requested Types If Coercion Not Possible #to_* Method Not Implemented on Object Calling Raises NoMethodError
When Using Implicit Coercions e.g. #to_str เราขอ Function Return String Object Only If Original Type Also Acts Like String For This Reason #to_str Only Implemented on String in Ruby Standard Library
How Ruby Uses Implicit Coercion
Other Than Being More Precise In What We're Asking During Coercion What Else Implicit Coercion Useful For? Turns Out Ruby Uses Implicit Coercions Itself Fair Bit Scenarios เช่น Combining Objects with +
Here Ruby Raise TypeError Since Can't Do Implicit Conversion from Name Type to String
If Implement #to_str on Class Ruby Knows How to Coerce Name Type
Same Works for Arrays and #to_ary
But #to_ary Used in More Scenarios We Can Use It Destructure Array into Separate Variables
It Also Does Conversion Object into Block Parameters
More Scenarios Implicit Coercion Methods Used เช่น #to_hash with ** Coerces Value to Hash with #to_hash Before Pass to parse_options Method
Enforcing Types (บังคับ Type)
Ruby Also Offers More Resilient Coercion Methods When Type Unknown และ We Want Make Sure Get Correct Type มี One for Every Basic Type (String(...), Integer(...), Float(...), Array(...), Hash(...), etc.)
Method String(...) First Tries Call #to_str on Value When Fails Calls #to_s Method Not All Objects Define #to_str Method Therefore Checking Both Implicit Coercion (#to_str) และ Explicit (#to_s) Casting Methods Increases Chances String Conversion Works และ Get Value You Want By First Calling Implicit Coercion More Likely Get Result Same Value But Coerced Type Not Something Like "#<Object:0x00007f8e6d053a90>"
You Should Only Implement Implicit Casting Methods for Objects That Act Like To Be Coerced Type e.g. #to_str for Your Own String Class
Other Than First Trying Implicit Coercion String(...) Helper Also Checks Returned Type #to_str Just Method Can Return Any Type Value Even Non-Strings To Ensure Get Value Requested Type String(...) Raises TypeError If Types Don't Match
Here Ruby Ignores Result of #to_str Because Returned nil Not String-type Instead Falls Back to #to_s Result
If #to_s Also Returns nil Thus Not Correct Type String(...) Will Raise TypeError
While More Reliable Enforcing Type Coercion Note Casting Helper Methods (String(...), Integer(...), etc.) Usually Bit Slower As They Need Perform More Checks on Given Value
In Conclusion
When You Want Make Sure Dealing with Right Type of Data for Object Type Coercion Useful Process ในบทความนี้เรา Refresh Knowledge Explicit Casting Helpers เหมือน #to_s, #to_i, #to_a และ #to_h เรายังดู Instances Implicit Helpers เหมือน #to_str, #to_int, #to_ary และ #to_hash Useful และ How They're Used by Ruby Itself
หวังว่าคุณพบ Type Coercion Overview นี้ Useful และ Actor Typecasting Analogy ตรงไปตรงมา As Always Let Us Know If Topic You'd Like Us to Cover If Questions/Comments Don't Hesitate Drop Us Line @AppSignal