與 Perl 和 Python 類似,Ruby 擁有出色的功能,是一種強大的文本處理語言。本文簡單介紹了 Ruby 的文本數據處理功能,以及如何使用 Ruby 語言有效處理不同格式的文本數據,無論是 CSV 數據還是 XML 數據。
Ruby 字符串
常用縮略詞
Ruby 中的 String 是容納、比較和操作文本數據的一種強大方法。在 Ruby 中,String 是一個類,可以通過調用 String::new 或向它分配一個字面值將它實例化。
向 Strings 賦值時,可以使用單引號(')或雙引號(")來包圍值。單引號和雙引號在為 Strings 賦值時有幾個差別。雙引號支持轉義序列使用一個前置反斜杠(/)并支持在字符串中使用 #{} 操作符計算表達式。而單引號引用的字符串則是簡單直接的文字。
清單 1 是一個示例。
清單 1. 處理 Ruby 字符串:定義字符串
message = 'Heal the World…'puts messagemessage1 = "Take home Rs #{100*3/2} "puts message1Output :# ./string1.rb# Heal the World…# Take home Rs 150
這里,第一個字符串使用一對單引號定義,第二個字符串使用一對雙引號定義。在第二個字符串中,#{} 中的表達式在顯示前計算。
另一種有用的字符串定義方法通常用于多行字符串定義。
從現在開始,我將使用交互式 Ruby 控制臺 irb>> 進行說明。您的 Ruby 安裝也應該安裝該控制臺。如果沒有安裝,建議您獲取 irb Ruby gem 并安裝它。Ruby 控制臺是學習 Ruby 及其模塊的一個非常有用的工具。安裝之后,可以使用 irb>> 命令運行它。
清單 2. 處理 Ruby 字符串:定義多個字符串
irb>> str = >>EOFirb>> "hello worldirb>> "how do you feel?irb>> "how r u ?irb>> EOF"hello, world/nhow do you feel?/nhow r u?/n"irb>> puts strhello, worldhow do you feel?how r u?
在 清單 2 中,>>EOF 和 EOF 中的所有內容都視為字符串的一部分,包括 /n(換行)字符。
Ruby String 類有一組強大的方法用于操作和處理存儲在它們之中的數據。清單 3、4 和 5 中的示例展示了部分方法。
清單 3. 處理 Ruby 字符串:連接字符串
irb>> str = "The world for a horse" # String initialized with a valueThe world for a horseirb>> str*2 # Multiplying with an integer returns a # new string containing that many times # of the old string.The world for a horseThe world for a horseirb>> str + " Who said it ? " # Concatenation of strings using the '+' operatorThe world for a horse Who said it ?irb>> str<<" is it? " # Concatenation using the '<<' operatorThe world for a horse is it?
新聞熱點
疑難解答