2011-06-14 17 views
7
long_string = <<EOS 
It was the best of times, 
It was the worst of times. 
EOS 

जो 53 देता है। क्यों? व्हाइटस्पेस गिना जाता है? यहां तक ​​कि अभी भी। हम 53 कैसे प्राप्त करते हैं?मुझे समझ में नहीं आता क्यों स्ट्रिंग.size देता है

इस बारे में कैसे?

 def test_flexible_quotes_can_handle_multiple_lines 
    long_string = %{ 
It was the best of times, 
It was the worst of times. 
} 
    assert_equal 54, long_string.size 
    end 

    def test_here_documents_can_also_handle_multiple_lines 
    long_string = <<EOS 
It was the best of times, 
It was the worst of times. 
EOS 
    assert_equal 53, long_string.size 
    end 

इस मामले क्योंकि% {मामले, 2 पंक्ति के अंत में प्रत्येक /n एक के रूप में चरित्र और थेरेस पहली पंक्ति से पहले एक, अंत में से एक माना जाता मायने रखता है, और उसके बाद में जबकि है EOS केस पहली पंक्ति से पहले एक और पहली पंक्ति के बाद एक है? दूसरे शब्दों में, पूर्व 54 और बाद वाले 53 क्यों हैं?

+0

ओह कृपया नहीं चार्ल्स डिकेंस उद्धरण ... – alternative

उत्तर

14

के लिए:

long_string = <<EOS 
It was the best of times, 
It was the worst of times. 
EOS 

String is: 
"It was the best of times,\nIt was the worst of times.\n" 

It was the best of times, => 25 
<newline> => 1 
It was the worst of times. => 26 
<newline> => 1 
Total = 25 + 1 + 26 + 1 = 53 

और

long_string = %{ 
It was the best of times, 
It was the worst of times. 
} 

String is: 
"\nIt was the best of times,\nIt was the worst of times.\n" 
#Note leading "\n" 

यह कैसे काम करता:

<<EOS के मामले में, लाइनों है कि यह पालन स्ट्रिंग का हिस्सा हैं। << के बाद << के समान टेक्स्ट और लाइन के अंत तक "मार्कर" का हिस्सा होगा जो यह निर्धारित करता है कि स्ट्रिंग समाप्त होने पर निर्धारित होता है (इस मामले में EOS स्वयं एक पंक्ति पर <<EOS से मेल खाता है)।

%{...} के मामले में, यह "..." के स्थान पर उपयोग किया जाने वाला एक अलग डिलीमीटर है। तो जब आपके पास %{ के बाद नई लाइन पर स्ट्रिंग शुरू हो रही है, तो वह नई पंक्ति स्ट्रिंग का हिस्सा है। है यही कारण है कि मैं भी गिना

a = " 
It was the best of times, 
It was the worst of times. 
" 
a.length # => 54 

b = "It was the best of times, 
It was the worst of times. 
" 
b.length # => 53 
+0

:

इस उदाहरण की कोशिश करो और आप कैसे %{...}"..." के रूप में ही काम कर रहा है देखेंगे। – kinakuta

संबंधित मुद्दे