Search code examples
rubyrubymine

Ruby - am I missing methods?


I recently started learning the Ruby programming language and encountered some strange behavior when writing some basic code. The code I had written below works fine when compiling on websites that allow me to run Ruby code, such as "repl.it", but when I try to compile my code in RubyMine, using the ruby-2.3.3-p222 SDK, or through CMD, my code does not result in any output. The code should output the number "10", but somehow does not output anything at all, except finishing with "exit code 0". What am I doing wrong or missing?

numbers = [1, 2, 3, 4]
numbers.map {|num| num*num}
numbers.select {|num| num%2==0}
numbers.inject do |sum, num|
  sum + num
end

Solution

  • You get no output, because you are not outputting anything. REPLs have a nice side effect where they usually show you the value of the last executed command. This is what you were seeing on repl.it. To get the expected output you need to print the result:

    numbers = [1, 2, 3, 4]
    numbers.map {|num| num*num}
    numbers.select {|num| num%2==0}
    result = numbers.inject do |sum, num|
      sum + num
    end
    p result