b.herring
b.herring

Reputation: 643

calling a ruby method in the ruby terminal

i have a method that gives an amount of square numbers depending on the number a user gives. eg if the users input is 5, the result will be 1, 4, 9, 16, 25. The method works. i was just wondering how to run this in the terminal. I know i need to do ruby squares.rb, which is the file name, but that just doesn't do anything afterwards. What i would like to happen is that someone could type squares(3), in the terminal, and get the result below it. im sure this is very simple aha, thanks.

def squares(input)
  numbers = (1..input)
  numbers.each do |number|
    puts number * number
  end
end

Upvotes: 0

Views: 209

Answers (3)

lacostenycoder
lacostenycoder

Reputation: 11186

Here's a variation that can be executed without prepending ruby to the filename and also doesn't make an infinite loop.

# make a file called square_loop.rb

#!/usr/bin/env ruby
def squares(input)
  numbers = (1..input)
  numbers.each do |number|
    puts number * number
  end
end

def setup_input_loop
  loop do
    puts "Print square from 1 to n. Please enter n or X to exit"
    input = gets.chomp
    exit if input.downcase == 'x' 
    squares(input.to_i)
    puts
  end
end

setup_input_loop

Then just make it executable with

chmod +x square_loop.rb

Then call it from your terminal with ./square_loop.rb

Though prepending ruby works too

ruby square_loop.rb

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246744

If you want a shell function that calls that ruby method:

squares() {
    ruby -e '
      def squares(input)
        numbers = (1..input)
        numbers.each do |number|
          puts number * number
        end
      end
      squares ARGV.shift.to_i
    ' -- "$1"
}

then

$ squares 3
1
4
9

If, by "ruby terminal", you mean irb then add that method to your ~/.irbrc file, then you can do

$ cat ~/.irbrc
def squares(input)
  numbers = (1..input)
  numbers.each do |number|
    puts number * number
  end
end

$ irb
irb(main):001:0> squares(3)
1
4
9
=> 1..3
irb(main):002:0> 

Just for fun, monkey patching the Integer class:

$ cat ~/.irbrc
class Integer
  def squares
    1.upto(self) {|n| puts n * n}
    self
  end
end
$ irb
irb(main):001:0> 3.squares
1
4
9
=> 3

Upvotes: 2

user3723506
user3723506

Reputation:

You can use gets method to get user input then parse it as int and call squares on it.

Try this

def squares(input)
  numbers = (1..input)
  numbers.each do |number|
    puts number * number
  end
end

def setup_input_loop
  loop do
    puts "Print square from 1 to n. Please enter n."
    input = gets.chomp.to_i
    squares(input)
    puts
  end
end

setup_input_loop

Upvotes: 0

Related Questions