-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?

3
  • What are you expecting to receive? 1212? Commented Jul 15, 2021 at 13:10
  • An array : [1,2,1,2] Commented Jul 15, 2021 at 13:10
  • 1
    What was wrong: do not need return and correct if-else statement Commented Jul 15, 2021 at 13:12

2 Answers 2

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

puts r.inspect
Sign up to request clarification or add additional context in comments.

Comments

0

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

7 Comments

IMHO, you shouldn't use next here. Could, but shouldn't. I'd personally do what's described in zswqa's answer.
Why? You give no explanation.
Code is easier to read when it has only one exit point instead of several.
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.
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.