เมธอด uniq ลบ ทั้งหมด Duplicate Elements จาก Array ได้
มาดูวิธีใช้!
ถ้ามี Array แบบนี้:
n = [1,1,1,2,3,4,5]
ตัวเลข 1 ซ้ำ — เรียก uniq จะลบตัวซ้ำ คืน New Array ที่มี Unique Numbers
ตัวอย่าง:
n.uniq # [1,2,3,4,5]
สังเกต uniq ไม่เปลี่ยน n (Original Array) — ต้อง uniq! หรือเก็บ Array ใหม่
ตัวอย่าง:
unique_numbers = n.uniq
ง่ายใช่ไหม? แต่มากคนไม่รู้ว่า uniq รับ Block ได้ — ด้วย Block ทำ Advanced things ได้
มาอธิบาย...
วิธีใช้ Ruby Uniq Method กับ Block
ตอนเรียก uniq มันสร้าง Hash จาก Array Elements — ทุก Element กลายเป็น Key ใน Hash
Keys ของ Hash ไม่ซ้ำ — ดึง Keys ทั้งหมดมาเป็น List ก็ได้ New Array ที่ Unique
ตอนนี้: ถ้าอยากเปลี่ยน "ความเป็น Unique" ให้ส่ง Block เข้าไป
ตัวอย่าง:
fruits = %w(orange apple banana)
"Orange" และ "Banana" ยาว 6 ตัวอักษรเท่ากัน
ถ้าใช้ uniq แบบนี้:
fruits.uniq(&:size) # ["orange", "apple"]
"banana" หายไป เพราะมัน Duplicate ตอนเปรียบเทียบจาก Size
อีกตัวอย่าง:
objects = [1, 2, "a", "b", :c, :d] objects.uniq(&:class)
ได้ Array Unique โดย Class:
[1, "a", :c]
เห็นพลังแล้วไหม? ส่ง Block ให้ uniq = กำหนดกฎ "ความเป็น Unique" เองได้
วิธีใช้ Uniq กับ Multiple Conditions
ใช้ Multiple Conditions ได้!
ทำแบบนี้: สมมติ Class User มี age, name, country — อยากได้คนละคนต่อ Country เดียวอายุเท่ากัน
ง่ายด้วย Block:
[david, petter, raphael].uniq { |person| [person.age, person.country] }
โค้ดนี้ ทั้ง 2 เงื่อนไขต้อง Match ถึงจะถือว่า Unique
มันทำงานยังไง?
ไม่มี Block: Object กลายเป็น Hash Key — มี Block: Yielded Value กลายเป็น Hash Key, Object กลายเป็น Hash Value
จากนั้น Ruby เอา Values มาเป็น New Array — รายละเอียด Implementation แต่น่าสนใจ จะแบ่งปัน
Summary (สรุป)
คุณเรียนรู้ uniq ใน Ruby แล้ว! วิธีใช้ ทำไมถึงประโยชน์ และ Mechanism ภายใน
ตอนนี้ Practice ด้วยเมธอดนี้ให้จดจำ — ขอบคุณที่อ่านครับ!