-3
r = "FBFB".split("").map do |char|
  if char == "F"
    return 1
  end
  if char == "B"
    return 2 
  end
end
puts r.inspect

I get nothing printed to console. What am I doing wrong?

Evgeni Petrov
  • 1,313
  • 13
  • 28

2 Answers2

1
r = "FBFB".split("").map do |char|
  if char == "F"
    1
  elsif char == "B"
    2 
  end
end

puts r.inspect
zswqa
  • 826
  • 5
  • 15
0

Turns out you cannot use return inside of a code block, but you should use next (source).

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Evgeni Petrov
  • 1,313
  • 13
  • 28
  • 1
    IMHO, you _shouldn't_ use `next` here. Could, but shouldn't. I'd personally do what's described in zswqa's answer. – Sergio Tulentsev Jul 15 '21 at 18:38
  • Why? You give no explanation. – Evgeni Petrov Jul 16 '21 at 10:00
  • Code is easier to read when it has only one exit point instead of several. – Sergio Tulentsev Jul 16 '21 at 16:02
  • Exit points are still two. Only difference is that code is shorter and it is using implicit return. Maybe that is why your prefer that piece of code? – Evgeni Petrov Jul 17 '21 at 13:45
  • 1
    Your comment contradicts itself. In absence of explicit returns (or equivalent statements, like `next` in this case), the body will always be executed in full and return the value of the last evaluated expression. That's what I call "one exit point". Always the last expression. And yes, that is precisely why I like that code. – Sergio Tulentsev Jul 17 '21 at 19:52
  • I do not contradict myself. We have difference of what "body" you mean. I mean the whole function, you mean the separate code paths in the if/else statement. – Evgeni Petrov Jul 18 '21 at 13:04
  • 1
    Nope, I mean the whole method body. Anyhow, this is getting us nowhere, so I'll stop. Using `next` here works, even if it isn't idiomatic ruby. – Sergio Tulentsev Jul 18 '21 at 17:59