Simple Ruby program does not produce output - ruby

I wrote a basic ruby program with TextMate in Mac OS:
def hello
puts " This works!"
end
name it Check-it.rb
I open a Terminal session, cd to the directory where the program is stored.
Then I type
ruby Check-it.rb
And nothing appears.
ruby -v
shows me the version, so it's there.
But with this and every other Ruby program, nothing appears.

As others already pointed out. The code in your file
def hello
puts " This works!"
end
defines a method called hello that outputs a string. But that method is never called. To actually call that method and run it change your code in the file to
def hello # this block defines the `hello` method
puts " This works!"
end
hello # this line calls the method `hello`

I think you are not calling this method at all. Call this method and then run your code, it will work.

Related

Not able to get result for def using ruby on mac osx

This is just a sample method I have created for testing purpose using Ruby on Mac OSX 10.12 but I don't get the desired output: Can anyone suggest please? I tried getting the result using both paranthesis and without (). It doesn't even throw any error.
def hi
puts "Hello World"
End
hi
hi()
hi("Hello Matz")`
Try this:
def hi
puts "Hello World"
end
hi
hi()
And this:
def greet(greeting)
puts greeting
end
greet("Hello Matz")
Note that in this line:
hi("Hello Matz")`
you have a tick mark at the end, so that is an error:
1.rb:5: syntax error, unexpected tXSTRING_BEG, expecting end-of-input
It doesn't even throw any error.
Then you aren't running that program.
I suggest you open a Terminal window (Applications/Utilities/Terminal.app), and type in:
$ vimtutor
vim is a free computer programming editor that comes with your Mac. Do the tutorial and learn how to use vim. To run a ruby program, you enter your code into a file, then save it as, say, my_prog.rb. Then you need to give that file to ruby to execute it. You execute a ruby program like this:
$ ruby my_prog.rb
You can create a directory for all your ruby programs like this:
$ mkdir ruby_programs
$ cd ruby_programs
To create a new file inside that directory, use vim:
~/ruby_programs$ vi my_prog.rb
Once you are done typing in your code, save the file, which will put you back at the prompt in Terminal, then you can run your program:
~/ruby_programs$ ruby my_prog.rb
Once you get comfortable with vim, and you feel confident running your ruby programs, consider installing macvim with the vivid chalk color scheme:
It's nicer to look at than plain vim.
Try editing your file so that it reads:
def hi
puts "Hello World"
end
hi
Some important differences to note: def and end are both case-sensitive. The inside of the function definition is indented by two spaces. Since the function takes no arguments, no parentheses are necessary on the call to hi on line 4.
Depending on your filename, enter the command ruby FILENAME and you should see the output Hello World
Ruby keywords are case sensitive. Your code uses End and you probably wanted to use end to mark the end of the hi method.
Because End is not the same as end (and End is not a keyword), irb keeps waiting for input and treats the other three lines as part of the hi method. As far as it can tell, its definition is not complete until it reaches the end keyword (all non-capital letters.)
The correct way to define the method is:
def hi
puts "Hello World"
end
Then you can call it using either hi or hi().
Calling it as hi("Hello Matz") (or hi "Hello Matz") throws an ArgumentError exception with the message wrong number of arguments (given 1, expected 0) because it is called with one argument but the definition of method hi doesn't specify anything about arguments (by its definition, the method hi doesn't accept any argument).

Ruby script won't execute

New to Ruby. I have created a very simple script called "hello.rb":
name = "Frederik"
puts = "Hello #{name}"
It will not execute (there is no output) in my terminal when I run "ruby hello.rb". I have checked that my editor (atom) is creating EOL's using "cat -e hello.rb" as suggested by "mu is too short" here: Why won't my Ruby script execute?. What could be causing this? I have attached a screenshot for reference.
Thank you!
puts = "Hello #{name}"
You're assigning "Hello #{name}" to a variable named puts, not writing it to STDIO.
remove the assignment operator and your output should display normally.

Ruby script - does not print 'Hello world!' from the command line

I have the following code in the script a.rb.
def main
puts "Hello World!"
end
When I run ruby a.rb on the command line, it doesn't display anything.
Why is this happening?
Unlike languages like C/C++/Java, Ruby does't have a main method that's called at program startup. The name main is not special.
You defined a method named main, but never call1 it.
def main
puts "Hello World!"
end
main # here, call the method
1: Technically, calling methods should be called sending messages, the idea comes from Smalltalk.

Is there a "main" method in Ruby like in C?

I'm new to Ruby, so apologies if this sounds really silly.
I can't seem to figure out how to write a "main" code and have methods in the same file (similar to C). I end up with a "main" file which loads a seperate file that has all the methods. I appreciate any guidance on this.
I spotted the following SO post but I don't understand it:
Should I define a main method in my ruby scripts?
While it's not a big deal, it's just easier being able to see all the relevant code in the same file. Thank you.
[-EDIT-]
Thanks to everyone who responded - turns out you just need to define all the methods above the code. An example is below:
def callTest1
puts "in test 1"
end
def callTest2
puts "in test 2"
end
callTest1
callTest2
I think this makes sense as Ruby needs to know all methods beforehand. This is unlike C where there is a header file which clearly list the available functions and therefore, can define them beneath the main() function
Again, thanks to everyone who responded.
#Hauleth's answer is correct: there is no main method or structure in Ruby. I just want to provide a slightly different view here along with some explanation.
When you execute ruby somefile.rb, Ruby executes all of the code in somefile.rb. So if you have a very small project and want it to be self-contained in a single file, there's absolutely nothing wrong with doing something like this:
# somefile.rb
class MyClass
def say_hello
puts "Hello World"
end
end
def another_hello
puts "Hello World (from a method)"
end
c = MyClass.new
c.say_hello
another_hello
It's not that the first two blocks aren't executed, it's just that you don't see the effects until you actually use the corresponding class/method.
The if __FILE__ == $0 bit is just a way to block off code that you only want to run if this file is being run directly from the command line. __FILE__
is the name of the current file, $0 is the command that was executed by the shell (though it's smart enough to drop the ruby), so comparing the two tells you precisely that: is this the file that was executed from the command line? This is sometimes done by coders who want to define a class/module in a file and also provide a command-line utility that uses it. IMHO that's not very good project structure, but just like anything there are use cases where doing it makes perfect sense.
If you want to be able to execute your code directly, you can add a shebang line
#!/usr/bin/env ruby
# rest of somefile.rb
and make it executable with chmod +x somefile.rb (optionally rename it without the .rb extension). This doesn't really change your situation. The if __FILE__ == $0 still works and still probably isn't necessary.
Edit
As #steenslag correctly points out, the top-level scope in Ruby is an Object called main. It has slightly funky behavior, though:
irb
>> self
=> main
>> self.class
=> Object
>> main
NameError: undefined local variable or method `main' for main:Object
from (irb):8
Don't worry about this until you start to dig much deeper into the language. If you do want to learn lots more about this kind of stuff, Metaprogramming Ruby is a great read :)
No there isn't such structure. Of course you can define main function but it won't be called until you do so. Ruby execute line by line so if you want to print 'Hello World' you simply write:
puts 'Hello World'
The question that you mentioned is about using one file as module and executable, so if you write
if __FILE__ == $0
# your code
end
It will be called only if you run this file. If you only require it in other file then this code will never run. But IMHO it's bad idea, better option is using RubyGems and there add executables.
Actually there is a main, but it is not a method; it's the top-level object that is the initial execution context of a Ruby program.
class Foo
p self
end
#=> Foo
p self
#=> main
def foo
p self
end
foo
#=> main
There is no magic main function in Ruby. See http://en.wikipedia.org/wiki/Main_function#Ruby
If you wish to run Ruby scripts like C compiled files, do the following:
#!/usr/bin/env ruby
puts "Hello"
and then chmod a+x file_name.rb. Everything that is below the first line will be run, as if it was contents of main in C. Of course class and function definitions won't give you any results until they are instantiated/invoked (although the code inside class definitions is actually evaluated, so you could get some output but this is not expected in normal circumstances).
Another way to write main() method is:
class HelloWorld
def initialize(name)
#name = name
end
def sayHello()
print "Hello ##name!"
end
end
def main()
helloWorld = HelloWorld.new("Alice")
helloWorld.sayHello
end
main

Ruby - redefining instance methods not working

My simple attempt to redefine instance methods are not working
class File
alias_method :old_atime, :atime
def atime(*args)
puts "helllllo"
old_atime(*args)
end
end
f = File.new("C:\\abc.txt","w")
puts f.atime
Any idea why?
I'm attempting to print "helllllo" everytime File#atime is called. Even alias old_atime atime is not working.
Is there something I'm doing wrong here?
Above code works perfectly as it should be. Puts "helllllo" writes "helllllo" in to your opened file. Puts inside the file instance meant for writing.
Just call f.close and open your file in text editor. You can see the content.
Yep, Ramesh is right. Try this:
class File
alias_method :old_atime, :atime
def atime(*args)
Kernel.puts "helllllo" # <---- Kernel method
old_atime(*args)
end
end
f = File.new("C:\\abc.txt","w")
puts f.atime
The issue is that 'puts' is defined in File for writing to files. You want the Kernel one which is used unless defined in a more specific scope.
This should work fine, but IO#puts writes to the IO object itself, not STDOUT. In other words, it's writing to the file.
Call f.atime a few times and then f.close within irb and you should see it printing helllllo to the file for each call to atime.
To print to STDOUT, you could use $stdout.puts or Kernel.puts.

Resources