【问题标题】:Return the for-loops and print txt file返回 for 循环并打印 txt 文件
【发布时间】:2017-06-28 13:33:44
【问题描述】:

我正在尝试一个代码,当 for 循环方法将生成字母并且这些字母将连接在一起并形成“abcd”时,它将打开一个文件,这将返回脚本并打印 txt 文件。 我尝试了不同的可能性,但目前只能停止脚本并打印所有时间字母,还打印文件。但从来没有能够让所有的人一起工作。

def words(target)
  filename = ARGV.first

 txt = open(filename)

  ('a'..'z').each do |i|
    ('a'..'z').each do |j|
      ('a'..'z').each do |h|
        ('a'..'z').each do |g|

   together = i+j+h+g
   print together

case together
 when together == target
  return print txt.read

           end
         end
       end
     end
   end
 end

words("abcd")

提前致谢。

【问题讨论】:

  • 所需的输入/输出是什么?

标签: ruby return argv


【解决方案1】:
('a'..'z').
  to_a.
  repeated_permutation(4).
  map(&:join).
  detect { |w| w == target }

【讨论】:

  • 我不知道repeated_permutation。不错!
【解决方案2】:

这不是case 的工作方式,您应该改用if

def words(target)
  filename = ARGV.first

 txt = open(filename)

  ('a'..'z').each do |i|
    ('a'..'z').each do |j|
      ('a'..'z').each do |h|
        ('a'..'z').each do |g|
          together = i+j+h+g
          print together

          if together == target
            return print txt.read
          end
        end
      end
    end
  end
end

words("abcd")

或者,如果你坚持使用case(出于某种原因):

case together
  when target
    return print txt.read
end

【讨论】:

  • 谢谢,我实际上也尝试过 if ,但仍然没有按预期工作。我不知道它实际上在哪里失败了,因为我想我尝试过那个选项不要,无论如何非常感谢你
  • 它适用于我,即打印从aaaaabcd 的所有字母组合,然后打印文件的内容。这不是你在问题中描述的吗?
  • 是的,这就是我想要的,不知道它在哪里失败,但打印字母并返回并打印 txt 文件没有发生。现在一切都好
猜你喜欢
  • 2021-08-18
  • 2020-07-28
  • 2015-04-26
  • 2020-05-01
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
相关资源
最近更新 更多