【问题标题】:Take a string and an array and return a modified merged array获取一个字符串和一个数组并返回一个修改后的合并数组
【发布时间】:2018-02-15 17:41:01
【问题描述】:

我必须构建一个采用数组和字符串的方法。该方法应返回一个包含三个元素的数组。它在索引 0 处的元素应该是字符串参数,并且不应该包含数组参数的最后一个元素。

对于数组:

best_teams = ([Boston Celtics, LA Lakers, Chicago Bulls]

和字符串:

my_team = ("Utah Jazz")

我期望输出:

[Utah Jazz, Boston Celtics, LA Lakers]

我试过这个:

def teams(best_teams, my_team)
  sec = my_team.split + best_teams
  return sec - sec[3].split
end

但它似乎不起作用。有什么想法吗?

【问题讨论】:

  • 这是学校作业吗?到目前为止,您尝试过什么?
  • 在不泄露太多信息的情况下,我建议在 ruby​​ 文档中搜索执行此操作的正确方法。为了给出提示,您需要查找类似于“prepend”的关键字,因为您想在数组前面添加一个字符串。 ruby-doc.org/core-1.9.3/Array.html
  • 你有没有尝试过任何
  • 我尝试使用 .split 将字符串转换为数组,然后使用 (+) 运算符合并两个数组,然后用 (-) 减去第二个数组的最后一个元素。不过好像没用
  • 您的阵列best_teams 有问题。应该是['Toronto Raptors', 'Boston Celtics', 'Houston Rockets', 'Golden State Warriors']

标签: arrays ruby


【解决方案1】:

看,假设以下值:

best_teams = ['Boston Celtics', 'LA Lakers', 'Chicago Bulls']
my_team = "Utah Jazz"

def teams(best_teams, my_team)
  # sec = nil
  sec = my_team.split + best_teams
  # the values at this point are
  # sec = ["Utah", "Jazz"] + ['Boston Celtics', 'LA Lakers', 'Chicago Bulls']
  # your single team name now become in an array with two values 
  # finally
  # sec = ["Utah", "Jazz", 'Boston Celtics', 'LA Lakers', 'Chicago Bulls']
  return sec - sec[3].split
  # ["Utah", "Jazz", 'Boston Celtics', 'LA Lakers', 'Chicago Bulls'] - ["LA", "Lakers"]
  # ["Utah", "Jazz", "Boston Celtics", "LA Lakers", "Chicago Bulls"]
end

请检查 https://apidock.com/ruby/String/split。 真正的问题是我猜你不知道拆分是如何工作的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2018-10-31
    • 2012-08-21
    • 1970-01-01
    • 2022-01-20
    • 2021-11-17
    • 2019-07-12
    相关资源
    最近更新 更多