0

I have this file.rb and when I run it from terminal, I want to delete a certain input value. However, the array remains the same. Any help, please?

   def delete
    print "Introduce the parameter for the delete action"
    delete_value = gets.chomp
    p @array.select { |e| e!= "#{delete_value}"}

    #@second_array = @array.reject! {|x| x == "#{delete_value}" }   
    #puts @second_array
   end
4

2 回答 2

0

你有一个数字数组:

@array = [-3,6,5,3,10,6,2,3,9,-3,-2,-5]

但你delete_value是一个字符串:

delete_value = gets.chomp

a == b对于每个 Fixnuma和 String都是错误的b(同样a != b总是正确的),因此您需要转换b为具有以下内容的数字:

delete_value = gets.to_i
@array.reject! { |x| x == delete_value }

Ruby 不会像某些语言那样自动在字符串和数字之间进行转换,您必须使类型匹配并手动执行类型转换。

于 2013-10-07T22:50:12.967 回答
0

此方法返回一个包含所有匹配项的新数组。你原来的数组确实不会改变。

如需进一步参考:http ://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-select

于 2013-10-07T22:06:34.637 回答