【问题标题】:Returning a string from a Ruby function从 Ruby 函数返回字符串
【发布时间】:2014-02-17 04:57:11
【问题描述】:

在这个例子中:

def hello
  puts "hi"
end

def hello
  "hi"
end

第一个和第二个函数有什么区别?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    在 Ruby 函数中,当返回值明确定义时,函数将返回它评估的最后一条语句。如果评估了print 语句,则该函数将返回nil

    因此,以下打印字符串hi返回nil

    puts "hi"
    

    相比之下,以下返回字符串hi

    "hi"
    

    考虑以下几点:

    def print_string
      print "bar"
    end
    
    def return_string
      "qux" # same as `return "qux"`
    end
    
    foo = print_string
    foo #=> nil
    
    baz = return_string
    baz #=> "qux"
    

    但是请注意,您可以通过printreturn 使用相同的功能:

    def return_and_print
      print "printing"
      "returning" # Same as `return "returning"`
    end
    

    上面将print字符串printing,但返回字符串returning

    请记住,您始终可以显式定义返回值

    def hello
      print "Someone says hello" # Printed, but not returned
      "Hi there!"                # Evaluated, but not returned
      return "Goodbye"           # Explicitly returned
      "Go away"                  # Not evaluated since function has already returned and exited
    end
    
    hello
    #=> "Goodbye"
    

    因此,总而言之,如果您想打印某个函数中的某些内容,例如控制台/日志,请使用print。如果你想返回那个东西离开函数,不要只是print它 - 确保它被显式或默认返回。

    【讨论】:

    • 好东西。非常彻底。 @zeantsoi
    【解决方案2】:

    第一个使用puts方法将“hi”写到控制台并返回nil

    第二个返回字符串“hi”并且不打印它

    这是一个 irb 会话中的示例:

    2.0.0p247 :001 > def hello
    2.0.0p247 :002?>   puts "hi"
    2.0.0p247 :003?> end
     => nil 
    2.0.0p247 :004 > hello
    hi
     => nil 
    2.0.0p247 :005 > def hello
    2.0.0p247 :006?>   "hi"
    2.0.0p247 :007?> end
     => nil 
    2.0.0p247 :008 > hello
     => "hi"
    2.0.0p247 :009 > 
    

    【讨论】:

      【解决方案3】:

      puts 将其打印到控制台。 所以

      def world
        puts 'a'
        puts 'b'
        puts 'c'
      end
      

      将打印 'a' 然后 'b' 然后 'c' 到控制台。

      def world
        'a'
        'b'
        'c'
      end
      

      这将返回最后一件事,所以你只会看到'c'

      【讨论】:

        猜你喜欢
        • 2010-12-14
        • 2014-12-07
        • 2014-11-06
        • 1970-01-01
        • 1970-01-01
        • 2021-12-08
        相关资源
        最近更新 更多