【问题标题】:I have a ruby array of filepaths (./dir2/chico.html) and I can't seem to get it to sort correctly我有一个红宝石数组文件路径(./dir2/chico.html),我似乎无法正确排序
【发布时间】:2014-09-09 16:36:54
【问题描述】:

所以我有我的数组:(这不是元素的确切顺序,只是一个例子)

myArray = {./dir2/chico.html, ./dir2/chico.rb, ./dir1/c.js, ./dir1/g.txt, ./dir1/d.css}

当我使用...进行排序时

myArray.sort

结果未排序...

./dir2/chico.html
./dir2/chico.rb
./dir1/c.js
./dir1/g.txt
./dir1/d.css

我想要的是将所有 dir1 文件放在 dir2 之前。 d.css 应该在 g.txt 之前。为什么不排序?

【问题讨论】:

  • 在 Ruby 中这是一个无效的赋值,并且这些不是花括号内的字符串,并且散列被封装在花括号中,而不是数组。 myArray = ['./dir2/chico.html', './dir2/chico.rb', './dir1/c.js', './dir1/g.txt', './dir1/d.css']; myArray.sort => ["./dir1/c.js", "./dir1/d.css", "./dir1/g.txt", "./dir2/chico.html", "./dir2/chico.rb"] 所以排序工作正常。

标签: ruby arrays sorting filepath


【解决方案1】:

建立在“user2891803”所说的基础上。您需要以不同的方式构造数组。您已经初始化了一个名为“myArray”的散列,让您对所使用的容器类型有一种错误的感觉。同样在编码时,这适用于所有语言,请尝试为变量命名,使其尽可能具有描述性、简洁性和精确性;不要害怕制作长变量名。下划线在可读性方面创造了奇迹!

myArray = ['./dir2/chico.html', './dir2/chico.rb', './dir1/c.js', './dir1/g.txt', './dir1/d.css']
puts myArray.sort

这应该适用于您正在尝试做的事情。 红宝石快乐!

【讨论】:

    【解决方案2】:

    来自 irb。

    irb(main):001:0> ary = ["./dir2/chico.html", "./dir2/chico.rb", "./dir1/c.js",   "./dir1/g.txt", "./dir1/d.css"]
    => ["./dir2/chico.html", "./dir2/chico.rb", "./dir1/c.js", "./dir1/g.txt", "./dir1/d.css"]
    irb(main):002:0> puts ary
    ./dir2/chico.html
    ./dir2/chico.rb
    ./dir1/c.js
    ./dir1/g.txt
    ./dir1/d.css
    => nil
    irb(main):003:0> puts ary.sort
    ./dir1/c.js
    ./dir1/d.css
    ./dir1/g.txt
    ./dir2/chico.html
    ./dir2/chico.rb
    => nil
    

    数组中的每个元素都需要用“”或''包围。
    数组的语法是 [ ],哈希是 { }

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      相关资源
      最近更新 更多