Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从Ruby方法返回变量?_Ruby - Fatal编程技术网

如何从Ruby方法返回变量?

如何从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 而字符数

返回“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
而字符数<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