我正在尝试编写自己的转置方法.我想知道不同形式的连接如何影响我的代码.
multi = [[1,3,5],[2,4,6],[7,9,8]]
new = Array.new(multi.length, [])
multi.each do |c|
c.each_with_index do |x,y|
new[y] += [x]
end
end
new #=> [[1, 3, 5], [2, 4, 6], [7, 9, 8]]
Run Code Online (Sandbox Code Playgroud)
multi = [[1,3,5],[2,4,6],[7,9,8]]
new = Array.new(multi.length, [])
multi.each do |c|
c.each_with_index do |x,y|
new[y] << x
end
end
new #=> [[1, 3, 5, 2, 4, 6, 7, 9, 8], [1, 3, 5, 2, 4, 6, 7, 9, 8], [1, 3, 5, 2, 4, 6, 7, 9, 8]]
Run Code Online (Sandbox Code Playgroud)
为什么他们不能以相同的方式工作?
IE为什么会像代码一样
var strArr = ["a", "b"];
console.log(strArr.reverse() === strArr ? true : false);
Run Code Online (Sandbox Code Playgroud)
如果反转数组的顺序不同,则打印为true?
你会如何以同样的方式对两个数组进行排序?
hey = %w[e c f a d b g]
hoo = [1,2,3,4,5,6,7]
hey.sort #=> [a,b,c,d,e,f,g]
hoo.same_sort #=> [4,6,2,5,1,3,7]
Run Code Online (Sandbox Code Playgroud) def longest_word(string)
words = string.split
idx = 0
while idx < words.length
if words[idx].length > words[idx + 1].length
longest = words[idx]
else
longest = words [idx + 1]
end
idx += 1
end
return longest
end
puts(longest_word("peas rambling tattoo") == "rambling")
Run Code Online (Sandbox Code Playgroud)
不断收到错误消息
longest_word.rb:5:in longest_word': undefined method
length'为nil:
来自longest_word.rb的NilClass(NoMethodError):15:in''
关于为什么会发生这种情况的任何信息都会很棒