How to simplify the following code with respond_to?

I have following code.

class Person
  def eat
    puts "I am eating"
  end
  def sleep
    puts "I am going to bed"
  end
  def laugh
    puts "Wahahaha"
  end
  def talk
    puts "...."
  end
end
little_boy = Person.new
puts 'Input an action'
request = gets.chomp
if request == 'eat'
  little_boy.eat
elsif request == 'sleep'
  little_boy.sleep
elsif request == 'laugh'
  little_boy.laugh
elsif request == 'talk'
  little_boy.talk
else
  puts 'Input error'
end

Now I would like to use method: respond_to? and send to simplify it.How
would it be?

class Person

def run action
eval action.to_s # calls a sttring as if it were a method
end
end

little_boy = Person.new

puts ‘Input an action’
request = gets.chomp

if little_boy.respond_to?( request )
little_boy.run request
else
puts “invalid action #{request}”
end

hope it helps

j

ps: All this functionality works for any ruby object, not only rails
models.

On Jul 7, 9:34 am, Ruby R. [email protected]

On 7 Jul 2008, at 13:04, Wolas! wrote:

class Person

def run action
eval action.to_s # calls a sttring as if it were a method
end
end

If you’re just going to call a method you’re better off just calling
send

Fred.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs