ruby - Print out multiple words with alternating uppercase and lowercase -
i cannot run code.
i want write down 50 words, words [0,2,4,6,8,...] uppercase , odd words lowercase.
what other ways of writing code there? should start new array , have index = []?
words = [] 50.times puts "please enter word:" words << gets.chomp end puts "these wonderful words. smart. keep up." %w(words).each_with_index {|word, index|} if index = word.even? puts word.upcase if index = word.odd? puts word.downcase end
you can't use %w(words):
words # => ["a", "b"] %w(words) # => ["words"] %w(...) converts every space-delimited string of characters separate string element in array:
%w(a 1) # => ["a", "1"] you can't interpolate words variable array way. there no reason to, you'll have array of string elements in words array since you've said it's an array using:
words = [] and
words << gets.chomp this not code:
if index = word.even? puts word.upcase if index = word.odd? puts word.downcase you can't test equality using =. instead assigning. ruby not interpreted basic:
a = 1 # => 1 == 2 # => false you can't word.even? or word.odd? because words aren't or odd, integers are.
1.even? # => false 1.odd? # => true 'foo'.even? # => # ~> -:3:in `<main>': undefined method `even?' "foo":string (nomethoderror) also, you'd need use closing end statements.
corrected like:
if index.even? puts word.upcase end if index.odd? puts word.downcase end but can written more succinctly , clearly:
folded_word = if index.even? word.upcase else word.downcase end puts folded_word
Comments
Post a Comment