2016-09-20 11 views
0

在一個聊天機器人,還有一個供機器人回答所確定的命令與短語,例如功能,Ruby中的隨機msg?

match /^Loggy, te amo/, :use_prefix => false 

    def execute(user) 
    if user.name.eql? 'Cquintero6' 
     @client.send_msg '/me besa a Carlos' 
     @client.send_msg 'Io también te jamón <3' 
    else 
     @client.send_msg "#{user.name}, ¿En serio crees que amaria a una basurilla como tú? Sáquese. " 
    end 
    end 

當我在聊天寫「Loggy,TE AMO」,機器人的答案,取決於在用戶上。問題是,我如何製作答案清單,以便機器人選擇一個隨機答案?謝謝!

+0

你問如何寫一個字符串數組,並選擇和隨機一個?或者你問在哪裏有一個你可以使用的「隨機短語」列表? –

+0

如何編寫一個字符串數組,然後選擇一個機器人! Yep –

+0

在我的回答中增加了一個ERB的例子 –

回答

0

構建一個數組( 「@ Client.send_msg」 的隨機字符串)很簡單:

phrases = [ 
    "a phrase", 
    "another phrase" 
] 

您也可以使用faker寶石。看到它的自述文件的選項,但這裏有一個例子:

phrases = 10.times.map { Faker::Company.catch_phrase } 

此時你只需要選擇一個隨機項,這是簡單的:

random_phrase = phrases.sample 
@client.send_msg random_phrase 

說你也想獲得一個隨機短語但根據運行時變量更改文本。下面是做這件事:

require 'erb' 
phrases = [ 
    "your name is <%= name %>" 
] 
name = user.name 
random_phrase = ERB.new(phrases.sample).result(binding) 
@client.send_msg random_phrase 

這編譯運行時ERB

+0

極其微小的挑剔,但是如果你想要一個10個Faker口頭禪的數組,爲什麼要使用'10.times.map {etc}'而不是'Array.new(10) {etc}'?另外,根據你在做什麼的複雜性,使用'String#%'比Erb簡單:'phrase = [「你的名字是%{name}」,...]; random_phrase = phrases.sample%{name:user.name}' – philomory

+0

感謝您顯示字符串插值方法。沒關係,但我認爲'10.times.map {}'更具可讀性(即鴨子打字,表達意圖) –