如何获取数组中字符串的最后一个字符

时间:2017-11-29 11:03:03

标签: ruby

我试图在这样的数组中获取字符串的最后一个字符:

isTaskCancelled()

我希望收到Down = ["up 1", "up 2", "up 3"] "1""2",并根据结果生成类似"3"的条件语句,这将运行此逻辑:< / p>

  • 如果最终字符为for.each,请"1" = @x
  • 如果最终字符为0,请"2" = @x
  • 如果最终字符为1,请"3" = @x

2 个答案:

答案 0 :(得分:3)

您的变量名称不应以大写字母

开头
> down = ["up 1", "up 2", "up 3"]
> numbers_ary = down.map{|s|s[-1]}
#=> ["1", "2", "3"]

> numbers_ary = down.map{|s| s.chars.last}
#=> ["1", "2", "3"]
  

根据结果

制作像for.each这样的条件语句

如果你创建一个数组循环并使用任何逻辑为同一个变量@x赋值,它将被覆盖并分配最后一个值。

但是根据你对逻辑的关注,可以这样做:

num = numbers_ary.sample #sample is used to pick random element from numbers_ary
case num
  when "1", "2", "3"
   @x = num.to_i - 1
end

答案 1 :(得分:-2)

以下答案具有rails依赖性。要删除该依赖关系,请将down.last更改为down.chars.lastdown[-1]

Down.each do |down|
  case(down.last)
  when '1'
   @x = 0
  when '2'
   @x = 1
  when '3'
   @x =2
  end
end

编辑:我在irb控制台上运行此操作后添加了我得到的输出,以便在我发布此答案之前添加关于我运行此操作的评论的人并且没有任何明确的评论

irb(main):014:0> Down=["up 1", "up 2", "up 3"]
=> ["up 1", "up 2", "up 3"]
irb(main):015:0> Down.each do |down|
irb(main):016:1* case(down.last)
irb(main):017:2> when '1'
irb(main):018:2> @x = 0
irb(main):019:2> puts "word: #{down}, last:#{down.last}, x: #{@x}"
irb(main):020:2> when '2'
irb(main):021:2> @x = 1
irb(main):022:2> puts "word: #{down}, last:#{down.last}, x: #{@x}"
irb(main):023:2> when '3'
irb(main):024:2> @x = 2
irb(main):025:2> puts "word: #{down}, last:#{down.last}, x: #{@x}"
irb(main):026:2> end
irb(main):027:1> end
word: up 1, last:1, x: 0
word: up 2, last:2, x: 1
word: up 3, last:3, x: 2
=> ["up 1", "up 2", "up 3"]