Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Ruby

คู่มือ Ruby String Methods ขั้นสูง: Mastering Text Manipulation

String คือลำดับตัวอักษร เป็นอ็อบเจ็กต์มีเมธอดมากมาย คู่มือเมธอดที่ใช้บ่อยและมีประโยชน์

1. String Length

"ruby".size  # 4  (length เหมือนกัน)

2. Check Empty String

"".empty?  # true
# blank = empty หรือแค่ whitespace

3. String Interpolation

name = "Jesus"
puts "Hello #{name}"
puts "The total is #{1+1}"  # code ภายใน interpolation ได้

เรียก to_s อัตโนมัติ

4. Extract Substring

string = "abc123"
string[0,3]   # "abc" (start index, length)
string[3,3]   # "123"
string[0..-2] # "abc12" (range, -2 = ตัว'avant-dernier)
string[0..2] = ""  # replace/remove substring

5. Check If Contains Substring

string = "Today is Saturday"
string.include?("Saturday")  # true
string.index("day")          # 2 (หา partial word, คืน index)

6. Pad String

"1101".rjust(8, "0")  # "00001101" (pad ซ้าย)
"1111".ljust(8, "0")  # "11110000" (pad ขวา)

7. Compare Ignoring Case

lang1 = "ruby"; lang2 = "Ruby"
lang1.upcase == lang2.upcase  # แนะนำวิธีนี้
# หรือ casecmp? (น้อยใช้)

8. Trim Whitespace

" test ".strip   # "test"
" test ".lstrip  # "test " (ซ้าย)
" test ".rstrip  # " test" (ขวา)

9. Prefix & Suffix

"ruby programming".start_with?("ruby")  # true
"ruby programming".end_with?("programming") # true
"bacon is expensive".delete_suffix(" is expensive") # "bacon" (Ruby 2.5+)

10. String → Array of Characters

"a b c d".split       # ["a","b","c","d"] (default space)
"a,b,c,d".split(",")  # ["a","b","c","d"] (CSV)
# CSV จริงควรใช้ CSV class จาก stdlib

11. Array → String

['a','b','c'].join      # "abc"
['a','b','c'].join("-")  # "a-b-c"

12. String → Integer

"49".to_i  # 49
"a".to_i     # 0 (ไม่มีตัวเลข)

13. Check If String Is Number

"123".match?(/\A-?\d+\Z/)   # true
"123bb".match?(/\A-?\d+\Z/) # false

Regex: เริ่มต้น (\A) optional dash (-?) ตัวเลข (\d+) จนจบ (\Z)

14. Append Characters (Concatenation)

string = ""
string << "hello" << " " << "there"  # "hello there"
# อย่าใช้ += สร้าง string ใหม่ทุกครั้ง ช้า!

15. Iterate Characters

"rubyguides".each_char { |ch| puts ch }
"rubyguides".chars  # ["r","u","b","y","g","u","i","d","e","s"]

16. Upper/Lowercase

"abcd".upcase   # "ABCD"
"ABCD".downcase # "abcd"

17. Multiline Strings

b = <<-STRING
aaa
bbb
ccc
STRING
a = %Q(aaa
bbb
ccc )

18. Replace Text (gsub)

"We have many dogs".gsub("dogs", "cats")  # "We have many cats"
"abccc".gsub("c", "")                     # "ab" (remove)
"We have 3 cats".gsub(/\d+/, "5")         # "We have 5 cats" (regex)
"the lord of the rings".gsub(/\w+/) { |w| w.capitalize }  # "The Lord Of The Rings" (block)
# sub = replace first match only, gsub = all matches

19. Remove Last Character

name = gets.chomp           # ลบ \n
"abcd?".chomp("?")          # "abcd" (Ruby 2.3+ optional arg)

20. Change Encodings

"abc".encoding        # Encoding:UTF-8
"abc".force_encoding("UTF-8")  # enforce encoding

21. Count Characters

"aaab".count("a")  # 3
"aaab".count("b")  # 1

22. Summary

เรียนรู้ string methods มากมาย: join/split, gsub, strip, interpolation, encoding, counting Bookmark และแชร์ให้เพื่อน Ruby developers!