How to remove quotes in an array in Ruby

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

which should this test pass.

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 received these feedback. Don't know how to get rid of the quote.

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

      

+3


source to share


4 answers


Try the following:

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

      



":#{temp}"

is a string, but this character is :"#{temp}"

string-interpolated.

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

      

+3


source


The problem is not with the quotes. The quotes mean the element is the type String

your spec expects Symbol

.

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

      

it 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


source


Simona Carletti has already provided a solution for your problem (using to_sym

), but you can improve your code even further:

Applies 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 on a single line using ternary if :

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

      

You may need to change your condition as it x.to_i != 0

returns false

for x = "0"

.

+2


source


":#{temp}"

generates a string starting with a colon.

But you want to translate a string temp

to a character, eg temp.to_sym

. Or do you want to create a character like this: :"#{temp}"

(note that the colon is before the string).

+1


source







All Articles