这是一种更好,更正确的编码方式吗?

时间:2016-03-14 02:49:22

标签: ruby

目标是创建一种反向按字母顺序排列动物名称的方法。

一本书指示以这种方式编写代码:

<modelVersion>4.0.0</modelVersion>

    <groupId>com.projects.api</groupId>
    <artifactId>messanger</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>messanger</name>

    <build>
        <finalName>messanger</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>mysql-connector</groupId>
                <artifactId>mysql-connector-java-5.1.38-bin</artifactId>
                <version>5.1.38</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>
        <!-- uncomment this to get JSON support
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>
        -->
    </dependencies>
    <properties>
        <jersey.version>2.22.2</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

但是,这段代码让我很困惑,所以我编写了一个更简单的代码。我想知道这个替代代码是否实现了与前一代码相同的目标。

def alphabetize(arr, rev = false)
  if rev
    arr.sort { |item1, item2| item2 <=> item1 }
  else
    arr.sort { |item1, item2| item1 <=> item2 }
  end
end

animals = ["Alligator", "Cat", "Elephant", "Dog", "Bear"]
puts "#{alphabetize(animals, true)}"

1 个答案:

答案 0 :(得分:0)

不,他们不一样。第一个是非破坏性的,但第二个是破坏性的。如果您在它们之后调用animals,则第一个返回原始订单,但第二个返回已排序的订单。

更好的方法是:

def alphabetize(arr, rev = false)
  arr.sort.send(rev ? :reverse : :itself)
end