carlos quintero carlos quintero - 2 months ago 18
Ruby Question

Random msg in Ruby?

In a chatbot, there's a function for the bot to answer to determined command with a phrase, for example, in

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


When I write "Loggy, te amo", the bot answers in the chat, depending on the user. The question is, how can I make a list of answers so the bot select one random answer? Thanks! (Random strings of " @Client.send_msg" )

Answer

Constructing an array is simple:

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

You can also use the faker gem. See its README for options, but here's an example:

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

At this point you just need to select a random entry, which is simple:

random_phrase = phrases.sample
@client.send_msg random_phrase

Say you also wanted to get a random phrase but change the text according to a runtime variable. Here's one way to do it:

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

This compiles the ERB string at runtime