2013-05-02 91 views
0

返回'hash'变量值的最佳方法是什么?如何从Ruby方法返回变量?

define_method :hash_count do 
    char_count = 0 
    while char_count < 25 do 
    hash = '' 
    hash << 'X' 
    char_count += 1 
    end 
end 
+0

你想完成什么? '而20 <25'是真实的 - 你只是定义了一个无限循环。 – tessi 2013-05-02 13:40:30

+1

但是,方法中最后执行的表达式的结果是返回值。除非你明确地调用'return'(如'return hash')。 – tessi 2013-05-02 13:41:49

+0

我的意思是20> 25!我希望能够在屏幕上打印4'x'! – Starkers 2013-05-02 13:44:01

回答

1

您必须在循环外定义hash。如果它在里面,你需要在每次迭代时重置它。

define_method :hash_count do 
    char_count = 0 
    hash = '' 
    while char_count < 25 
    hash << 'X' 
    char_count += 1 
    end 
    hash # returns the hash from the method 
end 

顺便说一句,你不必跟踪char_count。只要检查字符串的长度:

define_method :hash_count do 
    hash = '' 
    hash << 'X' while hash.length < 25 
    hash # returns the hash from the method 
end 
+0

为什么你用'while'? – 2013-05-02 14:19:53

+1

因为OP有。这是OPs代码的修正,而不是Ruby的推荐方式。 – 2013-05-02 14:33:34