[Ruby笔记]4. ruby 读写文件 File open read write new

Run

新建了一个文件temp.dat 存了一个数据,整数 100

PS C:\Users\Administrator\RubyCode> more temp.dat
100

PS C:\Users\Administrator\RubyCode> ruby c2fin2out.rb

Reading Celsius temperature value from data file...
The Celsius is :
100
Saving result to output file 'temp.out'

PS C:\Users\Administrator\RubyCode> more temp.out
212

Code

从文件temp.dat 读取数据,进行温度的计量单位转换,将运算结果输出到文件temp.out

File : c2fin2out.rb

puts "Reading Celsius temperature value from data file..."

num = File.read("temp.dat") # read data from file temp.dat
celsius = num.to_i # convert string to integer number
puts "The Celsius is : ",celsius

fahrenheit = (celsius * 9 / 5) + 32 # computation
puts "Saving result to output file 'temp.out'"

fh = File.new("temp.out","w") # current self is fh
fh.puts fahrenheit # write data into file
fh.close

Another

如果是需要将文件temp.dat的内容直接不修改写到文件temp.out的话,一行代码

File :  c2f_another.rb
open('temp.out','w').write(open('temp.dat').read)

Reference

《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
1.1.6. Keyboard and file I/O

: ; : ; : ; : ; : ;
: ; : ; : ; : ; : ;
: .v──┸──、.: :
.// / / / /\.:
/ / / / / ゙/ ∧.
⌒⌒⌒⌒┰⌒⌒⌒⌒
:∧ ∧ ┃
.(*゚Д゚)┃
 |  ⊃¶
 し-J
""""""""""""""""""""
http://emoji.vis.ne.jp/kasa.htm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值