9. converting between symbols and strings


#1

Here is my code not working :

strings.each do |lett|
if lett == "S"
symbols.push(lett.to_sym)
end
end
print symbols

I understand from the exercise explanation that if one of the strings stored in the VARIABLE STRINGS has the S letter then store that string in the VARIABLE SYMBOLS, so this let symbols with CSS and JAVASCRIPT stored with him.
I checked the forum before post this but none of the answers clarifies me.


#2

@jamona,

#strings="So so So iS a String"
strings="SsSiSaS"
#pre define an empty Array
symbols=[]
symbols1=[]
#split(" ") will use a =space-character= as Element-separator (you get words)
#split("") will lead to =every-character= being seen as an Element 
strings.split("").each do |lett|
   print lett
   if lett == "S"
      symbols.push(lett.to_sym)
      symbols1<<lett.to_sym
   end
end

print "\n==a new-line==\n"
print symbols
print "==a new-line==\n"
print symbols1

http://stackoverflow.com/questions/1484952/iterating-over-each-character-of-a-string-in-ruby-1-8-6-each-char
http://stackoverflow.com/questions/16289455/when-not-to-use-to-sym-in-ruby
http://stackoverflow.com/questions/2004491/convert-string-to-symbol-able-in-ruby
http://stackoverflow.com/questions/10569529/ruby-difference-between-array-and-arraypush


#4

nope, with that you only push all the strings in STRINGS inside symbols, i want to put inside symbols only strings with the S letter.


#6

You need to convert the strings to symbols.
push(string.to_sym) will do that. Why do you need to split or use if?


#7

Hi, this seems to work:

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]

Add your code below!

symbols = []

strings.each do |s|
t = s.to_sym
symbols.push(t)
end

If anyone can improve it, let me know. Thanks!


#8

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = []
strings.each {|s| symbols.push(s.to_sym)}


#9