# How to simplify the following code with respond\_to?

**URL:** <https://www.ruby-forum.com/t/how-to-simplify-the-following-code-with-respond-to/142363>\
**Category:** Rails\
**Created:** [July 7, 2008, 10:34am UTC](https://www.ruby-forum.com/t/how-to-simplify-the-following-code-with-respond-to/142363 "2008-07-07T10:34:33Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![learningruby](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/6bbea6/32.png) [@learningruby](https://www.ruby-forum.com/u/learningruby)\
**Post date:** [July 7, 2008, 10:34am UTC](https://www.ruby-forum.com/t/how-to-simplify-the-following-code-with-respond-to/142363/1 "2008-07-07T10:34:33Z")

</div>

I have following code.

```auto
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?

---

<div class="post-metadata">

**Author:** ![learningruby](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/6bbea6/32.png) [@learningruby](https://www.ruby-forum.com/u/learningruby)\
**Post date:** [July 7, 2008, 2:05pm UTC](https://www.ruby-forum.com/t/how-to-simplify-the-following-code-with-respond-to/142363/2 "2008-07-07T14:05:09Z")

</div>

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. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

---

<div class="post-metadata">

**Author:** ![learningruby](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/6bbea6/32.png) [@learningruby](https://www.ruby-forum.com/u/learningruby)\
**Post date:** [July 7, 2008, 2:09pm UTC](https://www.ruby-forum.com/t/how-to-simplify-the-following-code-with-respond-to/142363/3 "2008-07-07T14:09:51Z")

</div>

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.
