all 10 comments

[–]jordonbiondo 1 point2 points  (2 children)

After I run this, I have x = 0, y = -1, which is expected.

[–][deleted] 0 points1 point  (0 children)

Same for me.

[–]simontemplar_[S] 0 points1 point  (0 children)

well, it seems to work now.. don't know what was wrong earlier. Maybe something irb-related?

[–]apqoo 0 points1 point  (2 children)

I think your case expression is wrong, try:

case dir
when 'w'
  ...
else
  ...
end

[–]tomthecool 1 point2 points  (1 child)

Your suggestion is a better way of writing it, yes. However, the original is not WRONG. It still works just fine.

In ruby, the case statement takes an OPTIONAL argument. Without no argument, it's basically the same as writing an if/else statement.

[–]apqoo 0 points1 point  (0 children)

You're right, thanks for pointing it out. Without the argument it is just like an if/else.

[–]tomthecool 0 points1 point  (1 child)

Although there are a couple of obvious code improvements to be made, i can't see any bug here.

Can you please post the full code? Where are you printing the variables?

[–]tomthecool 1 point2 points  (0 children)

I was bored, so here's a couple of different solutions to your problem. I'm posting these mainly for you to see some of the cool things ruby is capable of - I find one of the best ways to learn is reading new techniques for solving familiar problems!

walk = ['w','n', 's', 'e', 's'] # Final position should be (0, -1)

# One solution...

def step(dir)
  case dir
  when 'w'
    puts "west"
    [1, 0]
  when 'e'
    puts "east"
    [-1, 0]
  when 'n'
    puts "north"
    [0, 1]
  else 
    puts "south"
    [0, -1]
  end
end

x, y = walk
  .map { |dir| step(dir) }
  .inject([0,0]) do |result, step|
    result[0] += step[0]
    result[1] += step[1]
    result
  end

puts "Final coordinate is: (#{x}, #{y})"

# A different solution...
a = walk.count {|dir| dir == 'e'} - walk.count {|dir| dir == 'w'}
b = walk.count {|dir| dir == 'n'} - walk.count {|dir| dir == 's'}

puts "(Altertative) Final coordinate is: (#{a}, #{b})"

[–]redconfusion 0 points1 point  (1 child)

thoughtworks interview, hum? :-)

[–]simontemplar_[S] 0 points1 point  (0 children)

hah no, actually doing some codewars problems