使用>比较两个字符串。 (大于符号)在Ruby? [英] Comparing two strings using > (greater than sign) in Ruby?

查看:583
本文介绍了使用>比较两个字符串。 (大于符号)在Ruby?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中遇到了一段代码,我的工作看起来很可怕。它应该显示两个数字之间的+/-增量,但它使用> 来比较数字字符串而不是数字。

I came across a piece of code in a project I'm working on that looks kind of scary. It's supposed to be displaying a +/- delta between two numbers, but it's using a > to compare strings of numbers instead of numbers.

我假设这段代码正常工作,所以我只是想了解Ruby在这种情况下如何比较这些字符串。

I'm assuming that the code is working as expected at the moment, so I'm just trying to understand how Ruby is comparing these strings in this case.

下面是替换变量的示例:

Here's an example with the variables replaced:

if '55.59(100)' > '56.46(101)'
  delta = '+'
else
  delta = '-'
end


推荐答案

String 包括 Comparable 模块,其定义 > > code>,< => )方法。因此,如果字符串a按字母顺序在字符串b之前,则 a< => b 返回 -1 < / code>。同样的< => 方法用于排序字符串,所以你可以想象在一个有序的字符串数组中,每个字符串'小于'

String includes the Comparable module, which defines <, >, >=, etc, based on the base class's compare (<=>) method. So if string a comes alphabetically prior to string b, a <=> b returns -1, and < returns true. The same <=> method is used for sorting strings, so you can imagine that in a sorted array of strings, each string is 'less than' its neighbor to the right.

这篇关于使用&gt;比较两个字符串。 (大于符号)在Ruby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆