根据if语句在数组中选择元素

时间:2022-11-11 17:26:30

I would like to print one of two strings dependently on the condition value in Ruby.

我想根据Ruby中的条件值来打印两个字符串中的一个。

Of course it can be always done in the most classic way:

当然,最经典的方法是:

if a==1 then puts "Yes!" else puts "No!" end

or even

甚至

puts (a==1 ? "Yes!" : "No!")

but I'm looking for more Ruby/Python way using lists/arrays. In Python it can be done with:

但是我正在寻找更多使用列表/数组的Ruby/Python方法。在Python中可以这样做:

print ['Yes', 'No'][1==2]

Is there any similar way to achieve this with Ruby? The code above (written in Ruby) doesn't work, because of boolean value as an index and it doesn't work even if I'd try (1==2).to_i...
Any ideas?

在Ruby中是否有类似的方法来实现这一点?上面的代码(用Ruby编写)不起作用,因为布尔值作为索引,即使我尝试(1= 2).to_i…什么好主意吗?

5 个解决方案

#1


5  

Provided that your a is numeric, you can do this:

如果你的a是数字的,你可以这样做:

puts ["Yes!", "No!"][a <=> 1]

#2


2  

I've never seen python way in ruby world

在ruby世界中,我从未见过python之道

but you can open class.

但是你可以上课。

class TrueClass
  def to_agreement   # any method name you want
    'Yes'
  end
end

class FalseClass
  def to_agreement
    'No'
  end
end

Or, I suggest use module

或者,我建议使用模块

module Agreementable
  def to_agreement
    self ? 'Yes' : 'No'
  end
end

TrueClass.include Agreementable
FalseClass.include Agreementable

Above both two way, You can use

以上两种方式,您都可以使用

true.to_agreement #=> 'Yes'
false.to_agreement #=> 'No'
(1==2).to_agreement #=> 'No'

It is ruby way.

这是ruby方式。

#3


2  

puts({true => 'Yes', false => 'No'}[a == 1])

#4


1  

puts (if a == 1 then "Yes!" else "No!" end)

put(如果a = 1,那么“Yes!”else“No!”结束)

#5


1  

You could add to_i method to TrueClass and FalseClass

您可以向TrueClass和FalseClass添加to_i方法

class TrueClass
    def to_i
        1
    end
end

class FalseClass
    def to_i
        0
    end
end


p ['yes', 'no'][(2==2).to_i]

#1


5  

Provided that your a is numeric, you can do this:

如果你的a是数字的,你可以这样做:

puts ["Yes!", "No!"][a <=> 1]

#2


2  

I've never seen python way in ruby world

在ruby世界中,我从未见过python之道

but you can open class.

但是你可以上课。

class TrueClass
  def to_agreement   # any method name you want
    'Yes'
  end
end

class FalseClass
  def to_agreement
    'No'
  end
end

Or, I suggest use module

或者,我建议使用模块

module Agreementable
  def to_agreement
    self ? 'Yes' : 'No'
  end
end

TrueClass.include Agreementable
FalseClass.include Agreementable

Above both two way, You can use

以上两种方式,您都可以使用

true.to_agreement #=> 'Yes'
false.to_agreement #=> 'No'
(1==2).to_agreement #=> 'No'

It is ruby way.

这是ruby方式。

#3


2  

puts({true => 'Yes', false => 'No'}[a == 1])

#4


1  

puts (if a == 1 then "Yes!" else "No!" end)

put(如果a = 1,那么“Yes!”else“No!”结束)

#5


1  

You could add to_i method to TrueClass and FalseClass

您可以向TrueClass和FalseClass添加to_i方法

class TrueClass
    def to_i
        1
    end
end

class FalseClass
    def to_i
        0
    end
end


p ['yes', 'no'][(2==2).to_i]