0

返回“哈希”变量值的最佳方法是什么?

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

1 回答 1

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
于 2013-05-02T13:51:58.470 回答