ruby 生成随机字符串_Ruby程序生成随机数
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 84Additional 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. =endputs "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 0puts "#{name} got Maruti 800" when 3puts "#{name} won iphone X" when 8puts "#{name} won Rs 10" when 6puts "#{name} won Samsung A50" elseputs "#{name}, Better luck next time" endOutput
輸出量
RUN 1 : Lucky Draw Enter your name Sunaina Sunaina, Better luck next timeRUN 2: Lucky Draw Enter your name Hargun Hargun, Better luck next timeRUN 3 : Lucky Draw Enter your name Kajal Kajal won iphone XRUN 4: Lucky Draw Enter your name Shivang Shivang got Maruti 800翻譯自: https://www.includehelp.com/ruby/generate-random-numbers.aspx
ruby 生成隨機字符串
總結
以上是生活随笔為你收集整理的ruby 生成随机字符串_Ruby程序生成随机数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 60级的战斗魔法师怎样过王的遗迹
- 下一篇: 哦,我的锦菲剧情介绍