Reputation: 13
Can someone please explain me why this code not working? I dont realy know much about ruby yet so hope you can help. It says I have syntax error in puts multi[is]
:
syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '<' puts multi[is]
Here's the code:
# multi = Array.new
# multi[0] = Array.new(2, 'hello')
# # multi[1] = Array.new(2, 'world')
# puts(multi[0])
# puts(multi[1])
multi = ['hest','hund','kat','fugl'] # names of animals
for i in multi # convert to
is = i.to_i
is++
# puts(i. inspect
puts multi[is] # her i have error says syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '<' puts
multi[is]
end
food = Array.new # a new arry
# 0 milk names for food
# 1 ost
# 2 kod
# 3 ris
Upvotes: 0
Views: 903
Reputation: 118299
Your is++
is the one causing error. Just write it is+=1
. In ruby there is no --
or ++
operator.
Straight from the documentation :
Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ...... To increment a number, simply write x += 1.
I re-written your code with some modification :
multi = ['hest','hund','kat','fugl'] # names of animals
index=-1
for name in multi
p "#{name} at #{index+=1}"
end
# >> "hest at 0"
# >> "hund at 1"
# >> "kat at 2"
# >> "fugl at 3"
Upvotes: 3
Reputation: 13014
Arup has already answered the question, but I wish to add the Rubyish tinge to your code which doesn't follow it's conventions.
multi = ['hest','hund','kat','fugl'] # names of animals
multi.each_with_index do |m, i|
puts "#{i+1} #{m}"
end
each_with_index
is Ruby enumerator which provides you with two block variables, one for element (here, m
) and one for index of corresponding element(here, i
)
Keep rubying. :)
Upvotes: 1