【问题标题】:Ruby get value from array using index [closed]Ruby使用索引从数组中获取值[关闭]
【发布时间】:2018-06-06 22:06:26
【问题描述】:

给定一个字母数组:

@recipients_list = ["Mum and Dad", "my best friend", "Brother"]

# > Here are the letters available to ship, select one by number
# > 1. Mum and Dad
# > 2. My best friend
# > 3. Brother

然后我作为用户输入 3(请注意,在这种情况下,Brother 是收件人姓名)。我的代码:

x = @recipient_list.each_with_index do |value, i|
  index_start = i + 1
  puts "#{index_start}.#{value}"
end
input = gets.chomp.to_i
puts x.at(input)

当用户按 3 时如何从数组中获取兄弟值?有人可以帮忙吗?

【问题讨论】:

    标签: arrays ruby indexing


    【解决方案1】:

    你必须使用puts x.at(input - 1),因为Ruby arrays' indexing starts with 0

    【讨论】:

    • 有趣的是,早四行他们仍然知道这一点。
    猜你喜欢
    • 2014-04-14
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2014-12-21
    • 2016-02-03
    • 2022-10-19
    • 1970-01-01
    相关资源
    最近更新 更多