英文:
Ruby concatenate two methods
问题
我刚刚开始学习Ruby,所以如果我做了什么很傻的事,请不要讨厌我这个问题。
我想要实现的是拥有两个方法:
def method1()
puts "foo"
end
def method2()
puts "bar"
end
然后我想要将这两个方法组合在一起,如下所示:
method1 + method2
以打印出"foo bar"。
在Ruby中是否有可能做到这一点?
英文:
I literally just started with Ruby so please do not hate for this question if I'm doing something really silly.
What I'd like to achieve is to have two methods:
def method1()
puts "foo"
end
def method2()
puts "bar"
end
and then I would like to put these two together as such
method1 + method2
to print out foo bar
Is this possible in ruby to do such a thing?
答案1
得分: 1
Rather than printing the values inside the functions, you should return the values from the functions.
def method1()
"foo"
end
def method2()
"bar"
end
Now you can do any of the following
puts method1 # Prints "foo"
puts method2 # Prints "bar"
puts method1 + method2 # Prints "foobar"
Having the puts
inside the method only allows the caller to do one thing with that method, namely print out the value it produces. Returning a string from the method allows callers to do whatever they please: print it, concatenate it, capitalize it, or anything else under the sun.
英文:
Rather than printing the values inside the functions, you should return the values from the functions.
def method1()
"foo"
end
def method2()
"bar"
end
Now you can do any of the following
puts method1 # Prints "foo"
puts method2 # Prints "bar"
puts method1 + method2 # Prints "foobar"
Having the puts
inside the method only allows the caller to do one thing with that method, namely print out the value it produces. Returning a string from the method allows callers to do whatever they please: print it, concatenate it, capitalize it, or anything else under the sun.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论