Reputation: 11
I cannot run my code.
I want to write down 50 words, but the even words [0,2,4,6,8,...]
are all uppercase and the odd words are lowercase.
What other ways of writing this code are there? Should I start a new array and have index = []
?
words = []
50.times do
puts "Please enter a word:"
words << gets.chomp
end
puts "These are your wonderful words. You are smart. Keep it up."
%w(words).each_with_index {|word, index|}
if index = word.even?
puts word.upcase
if index = word.odd?
puts word.downcase
end
Upvotes: 1
Views: 347
Reputation: 1454
You could use Enumerable#each_slice ?
words.each_slice(2){|w| p w[0].downcase; p w[1].upcase}
It requires an even number of words though.
Upvotes: 0
Reputation: 160551
You can't use %w(words)
:
words # => ["a", "b"]
%w(words) # => ["words"]
%w(...)
converts every space-delimited string of characters into a separate String element in an array:
%w(a 1) # => ["a", "1"]
You can't interpolate your words
variable into an array that way. There is no reason to, as you'll already have an array of String elements in your words
array since you've already said it's an an array using:
words = []
and
words << gets.chomp
This is not good code:
if index = word.even?
puts word.upcase
if index = word.odd?
puts word.downcase
You can't test for equality using =
. Instead that is assigning. Ruby is not interpreted BASIC:
a = 1 # => 1
a == 2 # => false
You can't do word.even?
or word.odd?
because words aren't even or odd, only integers are.
1.even? # => false
1.odd? # => true
'foo'.even? # =>
# ~> -:3:in `<main>': undefined method `even?' for "foo":String (NoMethodError)
Also, you'd need to use closing end
statements.
Corrected that would look like:
if index.even?
puts word.upcase
end
if index.odd?
puts word.downcase
end
But that can be written more succinctly and clearly:
folded_word = if index.even?
word.upcase
else
word.downcase
end
puts folded_word
Upvotes: 1
Reputation: 4561
There are several things here.
You are setting them equal using =
in your if
statements. You need to use ==
to test for equality whereas one =
sets equality. You're also missing an end
if you use two if
statements so instead use an if
/else
:
word = ["letter","booyah","sorry"]
word.each_with_index do |value, index|
if index % 2 == 0 #(this is a modulo, when no remainder it is even)
puts value.upcase
else
puts value.downcase
end
end
The result is:
LETTER
booyah
SORRY
Also, your chomp
method won't be defined unless you put something in the word
array first.
Upvotes: 0