ใช้เมธอดที่ถูกต้อง ประหยัดงาน โค้ดดีขึ้นทั้ง performance และ quality 7 เมธอดที่ควรรู้:
1. Integer#digits (Ruby 2.4+)
แยกหลักเลขของ Integer (ก่อนหน้า: to_s.chars.map(&:to_i).reverse)
123.digits # [3, 2, 1] (reverse order!)
หมายเหตุ: Fixnum/Bignum deprecated รวมเป็น Integer
2. The Tap Method
สร้างอ็อบเจ็กต์ เรียกเมธอด คืนค่าอ็อบเจ็กต์เดิม โดยไม่ต้อง temporary variable
# Before
user = User.new; user.name = "John"; user
# After
User.new.tap { |user| user.name = "John" }
3. Array#values_at
ดึงค่าหลายตำแหน่งไม่ต่อเนื่องครั้งเดียว:
arr = [1,2,3,4,5]
a, b, c = arr.values_at(0, 1, 4) # 1, 2, 5
# Hash ด้วย:
hash = {bacon: 300, chocolate: 200}
hash.values_at(:bacon, :chocolate) # [300, 200]
4. Hash#transform_values (Ruby 2.4+)
เปลี่ยนค่า hash ทั้งหมด คล้าย map แต่คืน hash (ไม่ใช่ array of arrays)
h = {bacon: 200, coconut: 300}
h.transform_values! { |v| v * 2 } # {:bacon=>400, :coconut=>600}
# ก่อนหน้า: h.each { |k,v| h[k] = v*2 }
5. Kernel#itself (Ruby 2.2+)
ดูไม่น่าสนใจแต่ powerful ร่วมกับ group_by:
words = %w(cat cat tiger dog cat)
words.group_by(&:itself).transform_values(&:size)
# {"cat"=>3, "tiger"=>1, "dog"=>1}
# transform_values ไม่มี: each_with_object({}) { |(k,v),h| h[k] = v.size }
Note: ใต้ Object class ใน docs แต่ defined ใน Kernel module
6. Array#count
นับ occurrences แทน counter + loop:
%w(a a a b c d a).count("a") # 4
[1,2,3,4,5,6].count(&:even?) # 3 (block ได้)
7. Enumerable#cycle
Repeat pattern หรือ toggle switch:
%w(a b c).cycle(3).to_a # ["a","b","c","a","b","c","a","b","c"] switch = %w(on off).cycle switch.next # "on", "off", "on", "off"...
ไม่ต้องเช็คค่าปัจจุบัน manual เรียก next Ruby จัดการให้
Summary
7 เมธอด: Integer#digits, tap, values_at, transform_values, itself, count, cycle รู้จักแล้วดี ไม่รู้ก็ลองใช้ดู!