"if statement" return based on source of script file

I’m fairly new to Ruby, so I’m hoping this is a simple issue, but I
can’t quite seem to get it to work.

I simply want an if statement in a method to return a value based on the
location of the running script file. I’ve tried several variations of
the following syntax. I’ve also tried similar syntax in a case
statement.

def method
if $0 == File.join(File.dirname(FILE) + ‘/…/source_dir/*.rb’)
return value
else
return value
end
end

Any help would be appreciated :slight_smile:

~Thanks

value is not defined in the method

also returning the same value for both cases makes the if redundant

Thanks for including the code, should also include the actual error
message
or example of incorrect behaviour

cheers

Chris H. wrote in post #1128493:

value is not defined in the method

also returning the same value for both cases makes the if redundant

Thanks for including the code, should also include the actual error
message
or example of incorrect behaviour

cheers

My apologies… I should have clarified; The code snip above is a very
bare bones example of what I’m trying to accomplish.

Essentially; “If the executing script’s directory location is this,
then do that.”

if $0(running script’s location directory) == this_directory
then do this

I know $0 only holds the name of the file of the executing script (from
what I can tell), so I think it’s just a matter of locating the right
global variable, or syntax. I’ve also tried File.dirname($0).

I’m not getting any errors per say, the if statement is just failing to
fire.

I hope that clarifies :slight_smile:

Take a look at:
http://www.ruby-doc.org/core-2.0.0/File.html
http://www.ruby-doc.org/stdlib-2.0.0/libdoc/pathname/rdoc/Pathname.html

Try this and you’ll get closer to what you want.

puts $PROGRAM_NAME # Same as $0
puts File.dirname(FILE)
puts File.absolute_path(FILE)
puts File.expand_path(FILE)
puts File.realpath(FILE)

mypath = “…/mylibs/”
puts File.expand_path(mypath)
if File.dirname(File.expand_path($PROGRAM_NAME)) ==
File.expand_path(mypath)
puts “The same”
else
puts “Not the same”
end

Best regards,
Abinoam

Abinoam Jr. wrote in post #1128513:

Take a look at:
http://www.ruby-doc.org/core-2.0.0/File.html
http://www.ruby-doc.org/stdlib-2.0.0/libdoc/pathname/rdoc/Pathname.html

mypath = “…/mylibs/”
puts File.expand_path(mypath)
if File.dirname(File.expand_path($PROGRAM_NAME)) ==
File.expand_path(mypath)
puts “The same”
else
puts “Not the same”
end

Best regards,
Abinoam

Yup, “File.expand_path(File.dirname $0)” is exactly what I was looking
for, thank you so much :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs