Seems like there should be a better way to do this:
def some_method(argument = 'foo')
bar = argument == 'foo' ? 'foo' : "#{argument.to_s}_foo"
# ... do things with bar ...
end
Any ideas? I've also played around with
bar = ("#{argument}_" if argument != 'foo').to_s + argument
but if anything that seems more complicated
From your example, you don't seem to need different variables for foo
and argument
at all (that would be different if you need them both later, but from your example it doesn't seem like it).
A simplification would be:
def some_method(bar = 'foo')
unless bar == 'foo'
bar = "#{bar}_foo"
end
# Do things with bar
end
Of course, you can do the unless
inline if you prefer:
bar = "#{bar}_foo" unless bar == 'foo'
Side note: You don't need to call to_s
when interpolating. Ruby will do that for you.
If argument
in your code does not become "foo"
other than by default, then you can do:
def some_method *argument
bar = [*argument, "foo"].join("_")
...
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.