How to delete quotation marks in an array in Ruby

让人想犯罪 __ 提交于 2021-01-27 13:40:11

问题


I am working on Test First Ruby with rspec examples testing...

which I need to pass this test.

it "tokenizes a string" do
    calculator.tokens("1 2 3 * + 4 5 - /").should ==
      [1, 2, 3, :*, :+, 4, 5, :-, :/]
  end

And here is my code

def tokens(str)
    data = str.split(' ')
    outcomes = []
    data.collect do |x|
      if x.to_i != 0
        outcomes.push(x.to_i)
      elsif x.to_i == 0
        temp = x.gsub('"', '')
        outcomes.push(":#{temp}")
      end
    end
    outcomes
  end

However, I got these feedback. Have no idea how to get rid of the quotation mark.

Failure/Error: [1, 2, 3, :*, :+, 4, 5, :-, :/]                                                                                                                               
       expected: [1, 2, 3, :*, :+, 4, 5, :-, :/]                                                                                                                                  
            got: [1, 2, 3, ":*", ":+", 4, 5, ":-", ":/"] (using ==)   

回答1:


Try this:

outcomes.push(:"#{temp}")

":#{temp}" is string but this :"#{temp}" symbol with string interpolation.

=>:"+".class
#> Symbol
=> ":+".class
#> String



回答2:


The problem are not the quotation marks. Quotes mean that the element is a String type, your spec expects a Symbol.

outcomes.push(":#{temp}")

should be

outcomes.push(temp.to_sym)

To give you an idea

2.1.2 :006 > :*.class
 => Symbol 
2.1.2 :007 > ":*".class
 => String 



回答3:


Simone Carletti already provided a solution for your problem (using to_sym), but you can further improve your code:

  • split(' ') can (in this case) be replaced with split (without arguments)
  • instead of elsif x.to_i == 0 you can use else
  • collect (or map) already creates and returns an array, you just have to provide the values

Applied to your code:

def tokens(str)
  str.split.map do |x|
    if x.to_i != 0
      x.to_i
    else
      x.to_sym
    end
  end
end

You can even write this in one line using a ternary if:

def tokens(str)
  str.split.map { |x| x.to_i != 0 ? x.to_i : x.to_sym }
end

You might have to modify your condition, since x.to_i != 0 returns false for x = "0".




回答4:


":#{temp}" generates a String that starts with a colon.

But you want to translate your temp string to a symbol, like this temp.to_sym. Or you want to build a symbol like this: :"#{temp}" (note that the colon is in front of the string).



来源:https://stackoverflow.com/questions/26926822/how-to-delete-quotation-marks-in-an-array-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!