ruby Flashcards
attr_accessorattr_readerattr_writer
A = B + C
What’s ARGV short for?
Argument vector, 紧跟在ex01.rb后面的参数比如,ARGV.first就是第一个参数
Difference puts/print?
- puts print new line2. puts ignore nil when displaying arrays
Difference: gets, STDIN.gets, STDIN.gets.chomp()
STDIN.gets.chomp() reads user input first;gets.chomp() reads ARGV first;.chomp() removes the /n at the end of the string.
default name of script?
$0
why close files?
to save some memory, or it’ll have to wait until garbage collection, which could come at who knows when
how to read/write a file?
File.open(from_file).read()File.open(to_file, “w”).write(content)
how to take more than one parameter?
use asterisk:def a_function (*args) print args # an arrayend
can we do maths inside of the parenthesis?
yes
how to reset read progress (rewind)?how to readlines?
input_file.seek(0, IO::SEEK_SET)input_file.readline()
a, b, c = [1, 2, 3, 4]
a => 1b => 2c => 3
how to require modules in irb?module Ex25 def self.break_words(stuff) words = stuff.split(‘ ‘) words endend
require ‘./ex25’Ex25.break_words(sentence)
how to generate [1, 2, 3, 4, 5]?
Array(1..5)(1..5).to_a
Range:(-1..-3).to_a(-3..-1).to_a(‘a’..’c’).to_a(‘a’…‘c’).to_a
[][-3, -2, -1][‘a’, ‘b’, ‘c’][‘a’, ‘b’]
how to cycle through an array?
a.cycle { |x| puts x } # goes on forevera.cycle(2) { |x| puts x } # execute twice