【问题标题】:Confused about many different ways of doing the same things对做同样事情的许多不同方式感到困惑
【发布时间】:2016-06-04 13:02:20
【问题描述】:

我目前正在 Codecademy 的 Ruby 课程和“哈希和符号”部分学习。这是我正在使用的代码:

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]

symbols = []

strings.each do |x|
    if x =='s'
        x.to_sym!
        symbols.push(x)
    end
end

此代码的目的是如果在字符串中遇到“s”,则将字符串的元素添加到符号变量中。但是,代码没有通过。我查看了一个解决方案,发现了这个:

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]

 symbols = []

 strings.each do |s|
     s= s.to_sym
     symbols.push(s)
end

我的问题是,Ruby 是否会识别数组中的实际“s”。这对我来说似乎是硬编码???

【问题讨论】:

    标签: ruby hardcode


    【解决方案1】:

    您发布的 Codeacademy 的解决方案实际上并没有解决您解释的问题。实际的解决方案如下所示

    strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
    symbols = []
    
    strings.each do |s|
        if s.downcase.include? 's'
            s= s.to_sym
            symbols.push(s)
        end
    end
    

    【讨论】:

      【解决方案2】:

      我会这样写:

      strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
      symbols = strings.select { |s| s =~ /s/i }.map(&:to_sym)
      #=> [:CSS, :JavaScript]
      

      解释:

      select 选择数组中所有需要条件的元素。这个例子的条件是:字符串s应该匹配不区分大小写的正则表达式/s/i(也就是字符串包含一个's'或'S')。也就是说strings.select { |s| s =~ /s/i } 将返回['CSS', 'JavaScript']

      map(&:to_sym) 返回数组,但首先在每个元素上调用to_sym

      另一个选项可能是:

      symbols = strings.map { |s| s.to_sym if s =~ /s/i }.compact
      

      【讨论】:

      • 或者干脆strings.grep(/s/i, &:to_sym)
      【解决方案3】:

      似乎您实际上是在尝试将每个字符串变成一个符号。如果是这种情况,运行 each 方法将简单地忽略任何 's'。要查看有效解决方案中实际发生的情况,让我们首先分解您的解决方案。

      strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
      symbols = []
      strings.each do |x|
      #So, if x is equal to a Class String of S
          if x =='s'
      #Turn that x into a symbol, which none of them should work
               x.to_sym!
               symbols.push(x)
          end
      end
      

      这是你说的代码。

       strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
       symbols = []
       #Similar each loop, but they used s and not x
       strings.each do |s|
       #Instead of checking whether there is a Class String of S, it is just
       #turning each value in the array into a symbol and pushing to the
       #symbols array
           s= s.to_sym
           symbols.push(s)
       end
      

      因此,总而言之,除非数组中有's',否则您的代码将永远无法工作,其中可能有s,但没有一个带有s的字符串。后者之所以有效,是因为它在没有 if 语句的情况下全部更改了它们。

      -编辑- 我从 Code Academy 看到了这个问题,我可以看到混乱来自哪里,这是这条指令 For each s in strings, use .to_sym to convert s to a symbol. 这有点令人困惑的伪代码,但让我重新格式化它,这样你就可以看到混乱发生在哪里 strings.each |s| { s = s.to_sym } 所以目标是使用s 作为你的空变量。您不需要检测s,只需将其用作空变量即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-22
        • 2013-07-20
        相关资源
        最近更新 更多