【问题标题】:How to compare values in groovy如何比较groovy中的值
【发布时间】:2021-07-03 21:08:25
【问题描述】:

我正在尝试将当前版本与程序的可用版本进行比较。我希望所有可用版本都大于当前版本。我不知道我是怎么做这个比较的:

groovy.txt 的示例:

11.6

groovy1.txt 的示例:

9.6.3 9.6.6 9.6.8 9.6.9 9.6.11 9.6.12 9.6.16 10.14 10.14 10.16 11.4 11.6 11.7 11.8 11.9 11.11 12.4 12.6

当我这样做时,由于av.findAll { it > cv } 中的转换转换,我遇到了以下错误:

Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String

【问题讨论】:

  • 提供groovy.txtgroovy1.txt 文件内容的样本很重要...

标签: groovy jenkins-groovy


【解决方案1】:

出现您的问题是因为 tokenize 返回的字符串列表无法与字符串进行比较。它发生在这一行:

av.findAll { it > cv }

对于cv 使用:

def cv = output.tokenize().collect { it.tokenize('.').collect { it as int } }.first()

对于av

def av = output2.tokenize().collect { it.tokenize('.').collect { it as  int } }

我将9.6.11 之类的版本号放入[9, 6, 11] 之类的数组中进行比较,直到找出数字是否更大。

然后编写代码比较版本:

av.findAll { 
    def isVersionGreater
    it.indexed().any { i, v ->
        if (cv[i] == v) return false
        isVersionGreater = v > (cv[i] ?: 0)
        return true
    }
    return isVersionGreater
}.collect { it.join('.') }

AFAIK,不幸的是,Groovy 没有与 [9, 6, 11] < [11, 1] 等效的 Python 版本来比较版本。

【讨论】:

  • 我还有一个要求。目前isVersionGreater 显示所有大于当前版本值的值。但我只想显示大于十进制数但小于整数的值。例如:11.6 是当前版本,可用版本列表是 [11.8,11.11,12.3],这里我只想显示 [11.8,11.11] 而不是 12,因为它大于当前值。
  • .findAll之后使用.remove { it[0] < cv[0] }
  • 另外,写一个新问题总是更好......
  • 抱歉下次一定会保留。但是现在,我收到了groovy.lang.MissingPropertyException: Exception evaluating property 'findAll' for java.util.ArrayList, Reason: groovy.lang.MissingPropertyException: No such property: findAll for class: java.lang.Integer 这个错误。
  • 把代码改成这样av.findAll.remove { it[0] < cv[0] } {
猜你喜欢
  • 2012-08-12
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多