2015-11-25 18 views
0

所有元素我有一個數組選擇相同的前三個字符在數組

["Hello, how are you", "Hello, I'm well", "What is your name"] 

我要選擇具有相同的前三個字符的所有元素。但是,我不知道元素是什麼。

編輯:重新思考這個問題。我真的在尋找一種將具有第一個x共同字符的元素進行分組的方法。它們可以是新數組或相同數組,但是元素排序正確。

+1

你是如何得到3個字符尋找?你可以在數組中的所有元素上運行一個正則表達式過濾器嗎? – pwilmot

+1

您的預期產出是多少?這是從你的問題 –

+0

預期產出不清是新數組,只有元素,如果他們有共同的前3個字符 – xeroshogun

回答

4

這完全是不明確的OP想要的東西,但如果有什麼其他的答案在這個時候給的是任擇議定書想要的東西,那麼這裏有一個簡單的方法:

a = ["Hello, how are you", "Hello, I'm well", "What is your name"] 
a.group_by{|e| e[0, 3]} 
+0

我投了大家的答案,因爲它們都是相似的,但這個工作的最好的「數組的元素用相同的三個字符開始」。謝謝! – xeroshogun

1

我認爲你的問題需要clarifitcation-如果你有一個數組["hello", "hello, what is your name?", "goodbye", "goodbye, user"]

在這種情況下,你將有2個可能/互斥組進行選擇。我會通過避免#select all all來解決這個問題:

- 創建一個空的result散列,並返回一個新的空數組。 - 在數組中的每個元素上進行反覆檢查,並將數組按前三位數字的一個鍵。 - 應用你所選擇的邏輯來返回散列或者你想要的鍵(s)/值(最大值,全部大於1等)。

def first_three_chars_match(strings) 
    result = Hash.new{ |hash,key| hash[key] = Array.new } 
    strings.each do |string| 
    key = string.slice(0,3) 
    result[key] << string 
    end 
    result 
end 

first_three_chars_match(["hello", "hello, what is your name?", "goodbye", "goodbye, user"]) 
=> {"hel"=>["hello", "hello, what is your name?"], "goo"=>["goodbye", "goodbye, user"]} 
1

下面是做到這一點的一種方法:

ary = ["Hello, how are you", "Hello, I'm well", "What is your name"] 
matches = ary.inject({}) do |hash, str| 
    chars = str[0,3]; 
    hash[chars] = (hash[chars] || []) << str; 
    hash 
end 
p matches 

程序的輸出:

{"Hel"=>["Hello, how are you", "Hello, I'm well"], "Wha"=>["What is your name"]} 
相關問題