Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在ruby中从数组中删除元素_Ruby - Fatal编程技术网

在ruby中从数组中删除元素

在ruby中从数组中删除元素,ruby,Ruby,我有一个数组,我想删除一些元素。我试过这个,但不起作用: @restaurants.each_with_index do |restaurant, i| if (restaurant.stars > 3) @restaurants.slice!(i) end end 如何操作?您可以在(索引)处使用Array\delete\u:请参阅 但是最好的方法是使用reject()或如果(),则删除。如果餐厅是一个数组,则可以使用pop,例如 a = [ "a", "b", "c",

我有一个数组,我想删除一些元素。我试过这个,但不起作用:

@restaurants.each_with_index do |restaurant, i|

if (restaurant.stars > 3)  @restaurants.slice!(i)     end

end
如何操作?

您可以在(索引)处使用
Array\delete\u
:请参阅


但是最好的方法是使用
reject
()或
如果
(),则删除。

如果餐厅是一个数组,则可以使用pop,例如

a = [ "a", "b", "c", "d" ]
a.pop     #=> "d"
a.pop(2)  #=> ["b", "c"]
a         #=> ["a"]

您将从Hck找到以下答案。但是您可以通过首先查看文档轻松地找到这一点。
@restaurants.reject!{|restaurant| restaurant.stars > 3}
@restaurants.reject! {|restaurant| restaurant.stars > 3}