在 Ruby 中,可以使用 push 方法或 << 運算符來在數組末尾添加數據。
push
<<
arr = [1, 2, 3, 4, 5] # 使用 push 方法 arr.push(6) puts arr # 輸出: [1, 2, 3, 4, 5, 6] # 使用 << 運算符 arr << 7 puts arr # 輸出: [1, 2, 3, 4, 5, 6, 7]
兩種方法都可以在數組末尾添加一個或多個數據項。