Ruby 为什么在while循环之外赋值变量会影响我的方法';什么样的行为?

Ruby 为什么在while循环之外赋值变量会影响我的方法';什么样的行为?,ruby,Ruby,我目前正在学习Ruby,并经历了一些实践问题。我的任务如下: 编写一个将输入作为字符串的方法。您的方法应该返回数组中最常见的字母以及它出现的次数 这就是我想到的: def most_common_letter(string) x = 0 holder = string[x] topcount = 0 topstring = 0 while string.length > x counter = 0 y = 0 while string.lengt

我目前正在学习Ruby,并经历了一些实践问题。我的任务如下:

编写一个将输入作为字符串的方法。您的方法应该返回数组中最常见的字母以及它出现的次数

这就是我想到的:

def most_common_letter(string)
  x = 0
  holder = string[x]
  topcount = 0
  topstring = 0
  while string.length > x
    counter = 0
    y = 0
    while string.length > y
      if holder == string[y]
        counter += 1
      end
        y += 1  
      if topcount == 0 || counter > topcount
        topcount = counter
        topstring = holder
       end
    end
    x += 1
  end
  return [topstring, topcount]
end
它返回找到的第一个值,但返回正确的topcounts数量。就我的一生而言,我不明白为什么在逐步完成我的代码后,我会这样做,但很明显我错过了一个明显的错误

在查看解决方案后,我提出的方案与解决方案之间的唯一区别是:

def most_common_letter(string)
  x = 0
  topcount = 0
  topstring = 0
  while string.length > x
    holder = string[x]
    counter = 0
    y = 0
    while string.length > y
      if holder == string[y]
        counter += 1
      end
        y += 1  
      if topcount == 0 || counter > topcount
        topcount = counter
        topstring = holder
       end
    end
    x += 1
  end
  return [topstring, topcount]
end
如果x仍在循环外重新分配,为什么在while循环内移动分配会影响行为


答案一定就在我面前,但我不知道为什么

如果删除一些行,可能会变得清晰:

def inside(string)
  x = 0
  while string.length > x
    holder = string[x]
    puts holder
    x += 1
  end
end

inside('abc')
在这里,
holder
在循环中设置三次,使用
x
的当前值,即
0
1
2

输出:

a
b
c
a
a
a
另一个:

def outside(string)
  x = 0
  holder = string[x]
  while string.length > x
    puts holder
    x += 1
  end
end

outside('abc')
这里,
holder
在循环外设置一次,使用
x
的初始值,即
0

输出:

a
b
c
a
a
a

您需要将其移动到循环内部,以便它在每次迭代时更新。否则,它将保留指定的第一个值(字符串中的第一个字母)。我意识到这不是你问题的一部分,但这个特殊问题可以用一行代码来解决:
string.chars.group_by{x}.map{char,occurations{char,occurations{char,occurations.count]}。sort_by{u124; uuu,num uocurances}。last
Oh,我想我真的没有意识到x+=1实际上就是x=x+1,因此x在循环中被重新分配,因此holder不会更新。出于某种原因,在我脑海中的某个地方,x+=1从循环外部重新分配x,而实际上,这就是我上面指定的。谢谢Stefan!!有时我觉得我忘记了对代码最基本的理解。。。