2016-01-12 50 views
1

我需要從完整句子中的「:」字符前面得到句子。如何獲得特殊字符(如:)的Ruby之前的句子?

ex。我有「此消息將自毀:Ruby是樂趣」

我只需要「這個消息將自毀」

這是我的方法

def destroy_message(sentence) 
    check_list = /[^:]/ 
    sentence_list = /^([a-zA-z\s]+) \:/ 

    if sentence =~ check_list 
     puts "have :" 
     firstConsonant = sentence.match(sentence_list) 
     puts firstConsonant 
    else 
     puts "Not have :" 
    end 
end 

destroy_message("This message will self destruct: Ruby is fun ") 

但我得到了來自看跌firstConsonant什麼。 我該如何解決它?

謝謝!

+1

[像這樣?](https://repl.it/BdNN) – potashin

+1

不能使用'「這條消息會自毀:Ruby很有趣」.split(':')[0]'=> ''這條消息會自毀'' – VKatz

回答

4

我只是split字符串在:並使用第一部分。使用複雜的正則表達式引擎可能會更快。

string = "This message will self destruct: Ruby is fun " 

string.split(':').first 
#=> "This message will self destruct" 
+0

你做了我在評論中的做法哈哈!!! – VKatz

+0

您可以通過將'2'作爲第二個參數傳遞給split來提高性能。 – sawa

+0

你也可以使用'string.lazy.split(「:」)。first'。 – Charles

0
# ruby.rb 
def destroy_message(sentence) 
    result, * = sentence.split(':') 
    unless result == "" # in case ":sentence_case" 
    puts "#{result}" 
    else 
    puts "Not have :" 
    end 
end 
destroy_message("This message will self destruct: Ruby is fun ") 
0

spickermann的回答會的工作,但除此之外,還有一個方法String#partition專門做這種事情(也可能是稍快)。

s, * = "This message will self destruct: Ruby is fun ".partition(":") 
s # => "This message will self destruct" 
-1

我什麼都沒有從puts firstConsonant。我該如何解決它?

你可以使用#Scan Methods

def destroy_message(sentence) 
    if sentence.scan(/^[^:]+/) 
    puts "have :" 
    firstConsonant = sentence.scan(/^[^:]+/) 
    puts firstConsonant[0] 
    else 
    puts "Not have :" 
    end 
end 

destroy_message("This message will self destruct: Ruby is fun") 

輸出

=> have : 
    This message will self destruct 

說明有關使用

    的正則表達式
  • ^聲稱我們在一條線的起點。
  • [^...]取反的字符類,它匹配任何字符,但不匹配該特定字符類中存在的字符。
  • + char類會重複一次或多次char類。
+0

換行符是如何相關的?雖然這可能有效,但與迄今爲止發佈的其他方法相比,它顯着較慢。當發佈更復雜的答案時,通常這是爲了邏輯清晰或性能,但從這個答案中,沒有什麼可以獲得。 – sawa

+0

@sawa我同意,但由於問題是關於編寫自己的方法而不是使用紅寶石內置方法,所以問問題的人希望知道給定代碼的問題。 – VKatz

+0

您是否看過我的評論? – sawa

相關問題