skip to Main Content

i’m newbie in Ruby. Today i was coding some home exercise and founding this behavior of my code: if i try to execute the same code in irb and VSC in second case i don’t get a single string of output.

Here’s example from VSC:

def even_or_odd(number)
  number.even? ? "Even" : "Odd"
end
even_or_odd(number)

This code don’t give me an output in VSC, but if i try to execute this code in irb it works fine:

irb(main):001:1* def even_or_odd(number)
irb(main):002:1*   number.even? ? "Even" : "Odd"
irb(main):003:0> end
=> :even_or_odd
irb(main):004:0> even_or_odd(32)
=> "Even"
irb(main):005:0> 

What’s the point?

2

Answers


  1. you need to have puts on your vsc

    def even_or_odd(number)
      number.even? ? "Even" : "Odd"
    end
    puts even_or_odd(32)
    

    change the var number to actual integer.

    but when in you run irb, it automatically show return value to console, that’s why it does not need puts.

    you can change this behavior by call irb --noecho, then you will need puts

    Login or Signup to reply.
  2. VSC and irb are two quite different tools. Irb is a ruby REPL (Read-Evaluate-Print-Loop environment). VSC is an IDE (Integrated Development Environment).

    REPLs such as irb or pry are designed to be used interactively. When they determine that a statement or block is complete in the read phase, they evaluate it, immediately print the results, and iterate to the next read attempt. This is very useful for testing and learning, since it gives immediate feedback on syntactic errors, logic errors, or conceptual misunderstandings. It is not how you want to run a working program. Once you have the logic of your program correct, you don’t want to drown the user by making them wade through the results of each and every calculation in a complex or repetitive task. Instead, working code uses explicit output statements (such as print, puts, p, pp in ruby) to specify when results are to be displayed.

    IDEs such as VSC are for writing whole programs or modules. You can put VSC into a REPL mode using the debugging tools, but the default behavior is to facilitate construction, and possibly running, of your program or module. There is no automated display of the program state when you’re not in debug mode, so if you want to see the results you need to use one of the output statements to explicitly control what to output and at what point in the logic. In your VSC code fragment, change even_or_odd(number) to puts even_or_odd(number).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search