Ruby 程式設計/Here 文件
外觀
為了建立多行字串,Ruby 支援Here 文件(Heredoc),這是一個源自Bourne shell 的特性,在Perl 和PHP 中也有使用。
要構建一個 Here 文件,<< 運算子後面緊跟一個識別符號,識別符號標記 Here 文件的結束。結束標記被稱為終止符。終止符之前的文字行將合併在一起,包括換行符和任何其他空白。
puts <<GROCERY_LIST
Grocery list
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*
* Organic
GROCERY_LIST
結果
Grocery list
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*
* Organic
如果我們向 puts 函式傳遞多個引數,那麼從 Here 文件建立的字串文字將被插入到引數列表中,無論 << 運算子出現在哪裡。
在下面的程式碼中,Here 文件(包含四個雜貨店商品和一個空行)作為第三個引數傳遞進來。我們得到與上面相同的輸出。
puts 'Grocery list', '------------', <<GROCERY_LIST, '* Organic'
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*
GROCERY_LIST
你也可以在引數列表中包含多個 Here 文件。我們在每個 Here 文件的末尾添加了一個空行,以便使輸出更易讀。
puts 'Produce', '-------', <<PRODUCE, 'Dairy', '-----', <<DAIRY, '* Organic'
1. Strawberries*
2. Blueberries
PRODUCE
1. Yogurt
2. Milk*
3. Cottage Cheese
DAIRY
執行此程式碼後的輸出是
Produce
-------
1. Strawberries*
2. Blueberries
Dairy
-----
1. Yogurt
2. Milk*
3. Cottage Cheese
* Organic
我們一直在我們的示例中使用 puts 函式,但是你可以將 Here 文件傳遞給任何接受字串的函式。
如果縮排 Here 文件內的行,則會保留前導空白。但是,終止符之前不能有任何前導空白。
puts 'Grocery list', '------------', <<Grocery_list
1. Salad mix.
2. Strawberries.
3. Cereal.
4. Milk.
Grocery_list
結果
Grocery list
------------
1. Salad mix.
2. Strawberries.
3. Cereal.
4. Milk.
如果為了可讀性,你還想縮排終止符,請使用 <<- 運算子。
puts 'Grocery list', '------------', <<-GROCERY_LIST
1. Salad mix.
2. Strawberries.
3. Cereal.
4. Milk.
GROCERY_LIST
但是,請注意,Here 文件內每行文字之前的空白仍然會保留。
Grocery list
------------
1. Salad mix.
2. Strawberries.
3. Cereal.
4. Milk.
你可能想知道 Here 文件是否遵循單引號 或雙引號 規則。
如果識別符號周圍沒有引號,就像我們之前的示例中那樣,那麼 Here 文件的主體將遵循雙引號規則。
name = 'Charlie Brown'
puts <<QUIZ
Student: #{name}
1.\tQuestion: What is 4+5?
\tAnswer: The sum of 4 and 5 is #{4+5}
QUIZ
這個示例的輸出是
Student: Charlie Brown
1.	Question: What is 4+5?
	Answer: The sum of 4 and 5 is 9
如果在識別符號周圍加上雙引號,則也會遵循雙引號規則。但是,不要在終止符周圍加上雙引號。
puts <<"QUIZ"
Student: #{name}
1.\tQuestion: What is 4+5?
\tAnswer: The sum of 4 and 5 is #{4+5}
QUIZ
要建立一個遵循單引號規則的 Here 文件,請在識別符號周圍加上單引號。
puts <<'BUS_SCHEDULES'
c:\napolean's documents\tomorrow's bus schedule.txt
c:\new documents\sam spade's bus schedule.txt
c:\bus schedules\the #9 bus schedule.txt
BUS_SCHEDULES
結果
c:\napolean's documents\tomorrow's bus schedule.txt
c:\new documents\sam spade's bus schedule.txt
c:\bus schedules\the #9 bus schedule.txt