小编Mc-*_*-Ac的帖子

__FILE__ == $ PROGRAM_NAME在ruby中意味着什么?

在查看Ruby中的代码时,我偶然发现了这个sintax.代码是:

if __FILE__ == $PROGRAM_NAME
  #some code...
end
Run Code Online (Sandbox Code Playgroud)

我想__FILE__是一个变量,它让我知道我所在文件的名称?但那么什么是$PROGRAM_NAMEsimbolize呢?另外,为什么这个if语句是必要的,因为程序可以使用或不使用它?

ruby variables special-variables

6
推荐指数
1
解决办法
4658
查看次数

如何在ruby中调用实例变量

我最近学会了如何创建类,虽然我不完全确定我应该使用它们的位置和原因.我用它们来创建具有类似方法/属性的对象.

我试着制作一个插科打码,但我偶然发现了一个我无法找到答案的问题.

class Person
  def initialize(name,health)
    @name = name
    @hp = health
  end

  def kick
    @hp -= 1
    if (@hp <= 0)
      puts "#{@name} got REKT!"
    end
  end

end

#Friends
michael = Person.new("Michael", 10)

10.times { michael.kick }
Run Code Online (Sandbox Code Playgroud)

即使这段代码有效,我想知道是否可以在课堂外使用/调用mihchael的hp?也许有点像哈希?michael[@hp]?但即使我将hp设置为全局变量,这也不起作用.是否所有检查对象属性的if/else语句都在类中?

非常感谢你

ruby variables if-statement instance

1
推荐指数
1
解决办法
935
查看次数

require_relative 不拉变量?

我一直在从 _why 的书中学习 Ruby,我尝试重新创建他的代码,但它不起作用。

我有一个world.rb文件;

puts "Hello World"

Put_the_kabosh_on = "Put the kabosh on"
code_words = {
    starmonkeys: "Phil and Pete, thouse prickly chancellors of the New Reich",
    catapult: "Chunky go-go",
    firebomb: "Heat-Assisted Living",
    Nigeria: "Ny and Jerry's Dry Cleaning (with Donuts)",
    Put_the_kabosh_on: "Put the cable box on"
}
Run Code Online (Sandbox Code Playgroud)

在我的另一个文件中, pluto.rb ;

require_relative "world"

puts "Hello Pluto"
puts code_words[:starmonkeys]
puts code_words[:catapult]
puts code_words[:firebomb]
puts code_words[:Nigeria]
puts code_words[:Put_the_kabosh_on]
Run Code Online (Sandbox Code Playgroud)

我知道我的require_relative作品,因为如果我在没有哈希部分的情况下运行 pluto.rb (只是 put "Hello World"),Hello World 就会被打印!

ruby variables ruby-on-rails require

1
推荐指数
1
解决办法
603
查看次数