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
Simona Carletti has already provided a solution for your problem (using to_sym
), but you can improve your code even further:
-
split(' ')
can (in this case) replace withsplit
(no arguments) - instead
elsif x.to_i == 0
you can useelse
-
collect
(ormap
) already creates and returns an array, you just need to provide values
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 to share