carlos quintero carlos quintero - 5 months ago 55
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 'Cquintero6'
@client.send_msg '/me besa a Carlos'
@client.send_msg 'Io también te jamón <3'
@client.send_msg "#{}, ¿En serio crees que amaria a una basurilla como tú? Sáquese. "

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" )


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 = { 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 =
random_phrase =
@client.send_msg random_phrase

This compiles the ERB string at runtime