简体   繁体   English

从ruby方法保存并调用多个变量

[英]Saving and calling multiple variables from ruby method

Maybe I've been staring at my Ruby book to the point where words don't mean anything anymore, but I thought I might as well ask. 也许我一直在盯着我的Ruby书,以至单词不再具有任何意义,但我想我也应该问。

What I'm looking to do is, rather than passing a bulk of variables through my function headers, or instead of using global variables, I'm looking to save my variables within a method, and call upon them at multiple times, throughout my functions. 我想要做的是,不是在我的函数头中传递大量变量,也不是在使用全局变量,而是在方法中保存变量,并在整个过程中多次调用它们职能。 What I'm realistically having an issue with, is scope. 我实际上遇到的问题是范围。

def DateGrab()
 print "\nEnter the date you're looking for (Month/Day): "
 longdate = gets.strip.split(/\/| /)
 if longdate[0].length > 3
   month = longdate[0].slice(0..2)
 else
   month = longdate[0]
 end
  day = longdate[1]
  year = `date | awk '{print $6}'`.strip
  grepdate = "#{day}/#{month}/#{year}"
  date = Date.parse("#{day}-#{month}-#{year}").strftime('%m%d%Y').strip
end

I'm looking to pass "grepdate" and "date" through multiple functions, and I feel that using a method would be easier, but every time I try to call the variable, I get a "undefined local variable or method" error. 我希望通过多个函数传递“ grepdate”和“ date”,我觉得使用方法会更容易,但是每次尝试调用变量时,都会出现“未定义的局部变量或方法”错误。

You want to look at instance variables. 您要查看实例变量。 You can set them via @grepdate = "something" These instance variables are accessible throughout your class and in all methods of that class. 您可以通过@grepdate = "something"设置它们。这些实例变量可在您的整个类以及该类的所有方法中访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM