0

I am testing in irb and everytime I require my file is is always returning false.

class Weather
def stormy
[false, true].sample
end
end

it seems to return false know matter what is in the array? I am unsure if it is my code or the way I am requiring file in irb. can anyone help Thank you

Stacca
  • 791
  • 2
  • 8
  • 19
  • What version of Ruby are you using, because this won't even run in 2.0 or 2.2 on my machine. It gives an `undefined method 'random'` error. – pjs Mar 21 '15 at 17:36
  • The question mentions "require my file", but there is no require being shown here. I'd like to see the calling code as well, including any require statements. – Wayne Conrad Mar 21 '15 at 20:55
  • The above code is in a Ruby file weather.rb. I open irb in terminal. type require_relative 'lib/weather.rb' and the result I get is true, then every other time I require it is false. I need it to be random. thanks – Stacca Mar 21 '15 at 21:38

2 Answers2

2

To pick randomly from an Array use sample:

def stormy
  [ false, true ].sample
end
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
shivam
  • 16,048
  • 3
  • 56
  • 71
  • thanks but seems to return false know matter what is in the array. – Stacca Mar 21 '15 at 18:00
  • that should not happen. How are you calling it? – shivam Mar 21 '15 at 18:01
  • in irb I am requiring the file the code is in require_relative 'lib/weather.rb' – Stacca Mar 21 '15 at 18:06
  • ok do this. Open irb - define this function - call it. You can see that it works perfectly. I think something else is wrong with other code. My guess - the way you are calling it. – shivam Mar 21 '15 at 18:09
  • thank you. can you clarify defining the function (sorry I noob). do you mean def storm = true ? – Stacca Mar 21 '15 at 18:12
1

The return value of require (or require_relative) indicates whether the file was loaded successfully or was already loaded. It has nothing to do with any methods that may be defined inside the file.

Once the file defining it has been loaded, to call your method (as currently defined) you would do

Weather.new.stormy
Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
  • Thank you! This has been helpful. As I am so fresh to ruby driving irb is all a little confusing thank you for your answer – Stacca Mar 22 '15 at 00:51