Ruby连接两个方法

huangapple go评论62阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月18日 03:56:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定