如何从Ruby方法返回变量?
返回“hash”变量值的最佳方法是什么如何从Ruby方法返回变量?,ruby,Ruby,返回“hash”变量值的最佳方法是什么 define_method :hash_count do char_count = 0 while char_count < 25 do hash = '' hash << 'X' char_count += 1 end end define\u方法:hash\u count do 字符计数=0 而字符数
define_method :hash_count do
char_count = 0
while char_count < 25 do
hash = ''
hash << 'X'
char_count += 1
end
end
define\u方法:hash\u count do
字符计数=0
而字符数<25则
哈希=“”
hash您必须在循环外部定义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
你想完成什么虽然20<25
是真的——您刚刚定义了一个无止境的循环。但是,方法中最后执行的表达式的结果是返回值。除非您显式调用return
(如returnhash
),我的意思是20>25!我想能够打印4'x'到屏幕上!试试'X'*4
,这会给你“XXXX”,这是一个循环实验!我没有什么奇怪的欲望想看一行4X,因为OP做了。这是对OPs代码的更正,而不是对Ruby方法的建议。
define_method :hash_count do
hash = ''
hash << 'X' while hash.length < 25
hash # returns the hash from the method
end