“您如何从Ruby数组中删除一个元素,而该元素只是另一个相反的元素?”

时间:2019-10-10 08:53:00

标签: arrays ruby duplicates

我需要从Ruby数组中删除一个反向词,但在获取正确的输出时遇到问题

我尝试了一种不同的循环方式,我使用了exec。


# Were going to get the first line of input which is the length of the wordlist and coerce to type fixnum
pword_list_length = gets.chomp.to_i

# Initialize an empty array to hold pword_list_length
pword_list = Array.new

# loop until we have all the lines of input pushed into the array
pword_list_length.times do
pword_list.push(gets.chomp)
end

# Next were going to check to see what word we have both forward and backwards
pword_list.each do |word|
bword = word.reverse!
  if pword_list.include? bword 
    print word.length
    print bword[bword.length/2]

  end
end```

```Expected Output:
3 y

Output
3y3c3e3y```

1 个答案:

答案 0 :(得分:0)

您要在此处更改列表

bword = word.reverse!

reverse!实际上将反转变量word的内容。在该列表之后,您一定会像刚将bword颠倒并将其分配给word一样包含bword

使用reverse(不带!)保持word不变。