ruby 生成随机字符串
产生随机数 (Generating random number)
The task is to generate and print random number.
任务是生成并打印随机数。
Generating random numbers means that any number can be provided to you which is not dependent on any pre-specified condition. It can be anything but must be within a range or limit. Ruby provides you the method for meeting the purpose.
生成随机数意味着可以为您提供任何数字,而不依赖于任何预先指定的条件。 它可以是任何东西,但必须在范围或限制之内。 Ruby为您提供了达到目的的方法。
Methods used:
使用的方法:
puts: This method is used to put strings as messages on the screen for creating a better interaction with the user.
puts :此方法用于将字符串作为消息放在屏幕上,以与用户建立更好的交互。
gets: This method is used to take input from the user.
gets :此方法用于接收用户的输入。
rand: This method is a pre-defined method in Ruby library which Is specifically defined for generating a random number. It can be invoked with parameters only otherwise it will give decimal results which are most of the times less than 0. The examples are:
rand :此方法是Ruby库中的预定义方法,专门为生成随机数而定义。 只能使用参数调用它,否则它将给出十进制结果,大多数情况下小于10。示例包括:
rand(6) rand(0..6) rand(9..24)
Variables used:
使用的变量:
up: It is used to store the upper limit.
up :用于存储上限。
lm: It is used to store the lower limit.
lm :用于存储下限。
Ruby代码生成随机数 (Ruby code to generate random numbers)
=begin
Ruby program to pick a random number from a range
=end
#input upper and lower limits
puts "Enter upper limit"
up=gets.chomp.to_i
puts "Enter lower limit"
lm=gets.chomp.to_i
#generate and print the random numbers
#between the given lower and upper limit
puts "The random numbers are..."
puts rand(lm..up)
puts rand(lm..up)
puts rand(lm..up)
puts rand(lm..up)
puts rand(lm..up)
Output
输出量
Enter upper limit
100
Enter lower limit
50
The random numbers are...
91
98
96
95
84
Additional program:
附加程序:
The same concept can be applied to create a lucky draw program in which user will enter his/her name and they will get to know what they have won based on the random number generated by the program.
可以将相同的概念应用于创建幸运抽奖程序,在该程序中,用户将输入他/她的名字,并且他们将基于该程序生成的随机数来知道自己赢了什么。
=begin
Ruby program for Lucky draw.
=end
puts "Lucky Draw"
#input the name
puts "Enter your name"
name=gets.chomp
#generate a random number
#pick a lucky number
chk=rand(8) #For getting a random value
#print the result based on the random
#generated lucky number
case chk
when 0
puts "#{name} got Maruti 800"
when 3
puts "#{name} won iphone X"
when 8
puts "#{name} won Rs 10"
when 6
puts "#{name} won Samsung A50"
else
puts "#{name}, Better luck next time"
end
Output
输出量
RUN 1 :
Lucky Draw
Enter your name
Sunaina
Sunaina, Better luck next time
RUN 2:
Lucky Draw
Enter your name
Hargun
Hargun, Better luck next time
RUN 3 :
Lucky Draw
Enter your name
Kajal
Kajal won iphone X
RUN 4:
Lucky Draw
Enter your name
Shivang
Shivang got Maruti 800
翻译自: https://www.includehelp.com/ruby/generate-random-numbers.aspx
ruby 生成随机字符串