【问题标题】:Array.map { |x| change value } is removing it from the array, why?数组.map { |x| change value } 正在从数组中删除它,为什么?
【发布时间】:2015-04-07 20:05:03
【问题描述】:

目标是将每个字母移动到字母表中的下一个字母, 在地图中,它成功地改变了字母,但是一旦我离开那里,这个值就会消失,除了元音。怎么会?

def LetterChanges(str)
  abc = [*("a".."z")]

  result = str.split(//)

  result.map! do |x| 

  if abc.include?(x)

    if x == "z"
       x = "A"
       else
       x = abc[abc.index(x)+1]

       # if you puts x here, you can see it changes value correctly

       if x == "a" || x == "e" || x == "i" || x == "o" || x == "u"
          x.capitalize!
          end
       end
    end

    #However here, the changed values that are not vowels disappear 
    # WHY is that happening, is the second if (vowel) affecting it? How?

end
puts "#{result.join}"  #<--- its only putting the vowels
return result.join  

end

LetterChanges("what the hell is going on?")  

【问题讨论】:

  • 当字符 (x) 不在 abc 中时,您的块值是多少?如果x'w' 怎么样?手动或在调试器中逐步执行代码。或者将其转换为 lambda (f = lambda do |x| if abc.include?(x) ... end),以便您可以使用各种输入轻松评估 irb 中的块。
  • 感谢 mu - 如果它不在 abc 中,我想要相同的值,所以我认为如果它不满足任何 if 条件,它只会保留 (x) 值。怎么没有发生?是什么让 (x) 失去了创建时的价值?

标签: ruby arrays dictionary enumerable


【解决方案1】:

传递给map! 的块在所有情况下都需要返回一个值才能使其工作。

http://www.ruby-doc.org/core-2.2.0/Array.html#method-i-map-21

def LetterChanges(str)
  abc = [*("a".."z")]

  result = str.split(//)

  result.map! do |x| 
    if abc.include?(x)
      if x == "z"
         x = "A"
      else
         x = abc[abc.index(x)+1]
         if x == "a" || x == "e" || x == "i" || x == "o" || x == "u"
            x.capitalize!
          end
      end
    end
    x
  end

  result.join  
end

【讨论】:

  • 感谢丹尼尔,快速提问:如果它遍历每个 x,如果它不符合所有 if 的标准,为什么它不返回 x?
  • 传递给map! 的代码块返回的值是最后一个被求值的表达式。一个iffalse 的计算结果为nil,因此如果执行到达if x == "a" || x == "e" || x == "i" || x == "o" || x == "u" 并带有一个不是元音的字母,那么该块将返回nil,而最后没有明确的x
【解决方案2】:

问题是你的如果。当 x 不是返回 nil 的元音时。

只需更改这一行

if x == "a" || x == "e" || x == "i" || x == "o" || x == "u"
    x.capitalize!
end

有了这个

x = %w{a e i o u}.include?(x) ? x.capitalize : x

【讨论】:

  • 谢谢丹尼尔,嘿,这里发生了什么事:“%w{aeiou}”,“%w”在说什么,“%w{ thesedontneedcommas?}”我相信你它有效,但我想了解那个简码
  • 是创建数组的其他格式。 %w 我说元素用空格分隔,{} 是限制所以 %{a e i o u} == ["a","e","i","o","u"]
  • 我可以推荐有关 Ruby 文字的文档吗:ruby-doc.org/core-2.1.1/doc/syntax/literals_rdoc.html
猜你喜欢
  • 2017-12-04
  • 2010-10-04
  • 2023-03-11
  • 2016-02-09
  • 2020-07-13
  • 2021-11-28
  • 2021-04-19
  • 1970-01-01
  • 2012-08-31
相关资源
最近更新 更多