# How to refactor these code?

**URL:** <https://www.ruby-forum.com/t/how-to-refactor-these-code/182288>\
**Category:** Ruby\
**Created:** [January 26, 2010, 3:53am UTC](https://www.ruby-forum.com/t/how-to-refactor-these-code/182288 "2010-01-26T03:53:07Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rubyernewbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9dc877/32.png) [@rubyernewbie](https://www.ruby-forum.com/u/rubyernewbie)\
**Post date:** [January 26, 2010, 3:53am UTC](https://www.ruby-forum.com/t/how-to-refactor-these-code/182288/1 "2010-01-26T03:53:07Z")

</div>

def ss(s = ‘hello’, yeah = nil)  
if yeah  
puts “something”  
else  
puts “other thing”  
end

#code continue …  
end

I have this method, use it like that:

ss(‘hi’, yeah = true)  
ss(‘hello’)  
ss(‘fuck’, yeah = true)  
ss(‘hello’,yeah = true)

very ugly… sometimes I just need to passed yeah = true, but I have to  
added ‘hello’ first.

what should I do?

---

<div class="post-metadata">

**Author:** ![rubyernewbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9dc877/32.png) [@rubyernewbie](https://www.ruby-forum.com/u/rubyernewbie)\
**Post date:** [January 26, 2010, 5:13am UTC](https://www.ruby-forum.com/t/how-to-refactor-these-code/182288/2 "2010-01-26T05:13:13Z")

</div>

A little more context would be helpful, but you could do something  
like:

def ss(options={})  
s = options.delete(:s) || “hello”  
yeah = options.delete(:yeah)

puts (yeah ? “something” : “other thing”)

#code continue …  
end

ss(:hello =\> ‘hi’, :yeah =\> true)  
ss(:yeah =\> false)

and so on.

Burke L.

---

<div class="post-metadata">

**Author:** ![rubyernewbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9dc877/32.png) [@rubyernewbie](https://www.ruby-forum.com/u/rubyernewbie)\
**Post date:** [January 26, 2010, 9:23am UTC](https://www.ruby-forum.com/t/how-to-refactor-these-code/182288/3 "2010-01-26T09:23:05Z")

</div>

2010/1/26 Zhenning G. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> def ss(s = ‘hello’, yeah = nil)  
> if yeah  
> puts “something”  
> else  
> puts “other thing”  
> end
> 
> #code continue …  
> end

What do you need argument “s” for?

> what should I do?  
> Define two methods. At least from the interface this is cleaner.  
> Generally flags that control method behavior are considered bad  
> practice because they tend to make the implementation of a method more  
> complex and tie things together that might really be independent (just  
> consider what happens if you inherit a class and want to change only  
> one of the two variants).

Note, you can still share an internal implementation under the hood e.g.

def ss1  
ss\_impl “something”  
end

def ss2  
ss\_impl “other thing”  
end

private  
def ss\_impl(x)  
…  
end

But your example is really a bit short to come up with a definitive  
answer how to improve this.

Kind regards

robert
