How do I make this code more elegant? I have:
alpha = "lorem ipsum"
alpha = alpha + "\n" + "more text"
alpha = alpha + "\n" + "look I'm woody, howdy howdy howdy"
#etc
I would like:
alpha.puts "lorem ipsum"
alpha.puts "more text"
alpha.puts "look I'm woody, howdy howdy howdy"
# etc
or, perhaps, alpha.append as it is not taken. I attempted:
class String
def append(apnd)
self.to_s + "\n" + apnd
end
end
but that doesn't modify it, only returns it. And I learned from searching you can't modify the self. I get the same problem with:
def apnd(a,b)
a = a + "\n" + b
end
which I find very confusing as I thought Ruby passes the object by reference, rather than by value.
I saw "Custom + Method in Ruby String" and a couple other Stack Overflow posts.
Update:
Aha, for the apnd method I can follow "'pass parameter by reference' in Ruby?" but that means I can't have apnd(alpha, "stuff"), it would have to be apnd(:alpha, "stuff", binding) which doesn't reduce repetition as I have to pass binding into every single method.
<<syntax, but do I really want to writealpha << "\n" << "stuff"? It doesn't seem very elegant to have to include the "\n" every time["\n","stuff"].inject(alpha,:<<)?alphais a collection of lines. You could use an array and invokejoin("\n").putsis used to output to a stream, not append to an object/container. Usingputsto append would be confusing to others who are using your code.appendorconcatare more acceptable because other classes that have that method use it to add something to a container. It might seem like a small thing, but it's important to making a language flow as we write in it.