# Generic method without case/when?

**URL:** <https://www.ruby-forum.com/t/generic-method-without-case-when/67633>\
**Category:** Ruby\
**Created:** [February 14, 2006, 3:19am UTC](https://www.ruby-forum.com/t/generic-method-without-case-when/67633 "2006-02-14T03:19:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![PaatschS\_Bernd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/fbc32d/32.png) [@PaatschS\_Bernd](https://www.ruby-forum.com/u/PaatschS_Bernd)\
**Post date:** [February 14, 2006, 3:19am UTC](https://www.ruby-forum.com/t/generic-method-without-case-when/67633/1 "2006-02-14T03:19:32Z")

</div>

I like to write a generic method that calls different functions  
depending on  
what string I parse to the method (see example) without having to use a  
case-when? Is there a way to do that?

Process\_easy(“aFile”, “Summer”)

def process\_easy(file, what)

```
if file.include?("#{what}#{NL}") then
  constructor = CategoriesFactory.start_what # this is wrong. I like 

```

to  
substitute and have: constructor = CategoriesFactory.start\_summer  
start = file.index(“Summer#{NL}”)  
return constructor

# etc

end

-Bernd

---

<div class="post-metadata">

**Author:** ![PaatschS\_Bernd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/fbc32d/32.png) [@PaatschS\_Bernd](https://www.ruby-forum.com/u/PaatschS_Bernd)\
**Post date:** [February 14, 2006, 3:38am UTC](https://www.ruby-forum.com/t/generic-method-without-case-when/67633/2 "2006-02-14T03:38:35Z")

</div>

Paatsch, Bernd wrote:

> substitute and have: constructor = CategoriesFactory.start\_summer  
> start = file.index(“Summer#{NL}”)  
> return constructor
> 
> # etc
> 
> end
> 
> -Bernd

Check the Object#send method:

obj.send(‘method’, arg1, arg2…)

---

<div class="post-metadata">

**Author:** ![PaatschS\_Bernd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/fbc32d/32.png) [@PaatschS\_Bernd](https://www.ruby-forum.com/u/PaatschS_Bernd)\
**Post date:** [February 14, 2006, 10:38am UTC](https://www.ruby-forum.com/t/generic-method-without-case-when/67633/3 "2006-02-14T10:38:32Z")

</div>

Paatsch, Bernd wrote:

> like to substitute and have: constructor =  
> CategoriesFactory.start\_summer start = file.index(“Summer#{NL}”)  
> return constructor
> 
> # etc
> 
> end

Difficult to tell from this example. You could use send as Tim  
suggested.  
But you might as well use a different approach:

- extract a class name from the string
- extract another string from the string and map that via a Hash to a  
lambda / class whatever

MAP = {  
“what” =\> lambda {|x| puts “doing what #{x}”},  
“Summer” =\> lambda {|x| puts “it’s summer”},  
}  
def process\_easy(file)  
cmd = MAP[file[/\w+$/m]] and cmd[file]  
end

Kind regards

```
robert
```
