发新话题
打印

[Ruby] ruby 练习场

本主题由 admin 于 2008-3-16 16:46 移动

ruby 练习场

10.times { puts "Hello!" }

a = 1
b = 2
puts  a + b
puts "Hello, world!"


class Song
  def initialize(a)
  end
end

song1 = Song.new("Ruby Tuesday")
song2 = Song.new("Enveloped in Python")

puts  "gin joint".length
puts  "Rick".index("c")
puts  ((-1942).abs)

number = -1234
number = number.abs
puts number



def say_goodnight(name)
  result = "Good night,say goodbye " + name
  return result
end

puts say_goodnight("John-Boy")
puts(say_goodnight("John-Boy"))
puts "And good night,\nGrandma"


def say_goodnight2(name)
    result = "Good night, #{name.capitalize}"
    return result
  end
puts say_goodnight2('Pa')
puts say_goodnight2('uncle')

$greeting = "hello"
@name = "Prudence"

puts "#$greeting,#@name"


def say_goodnight3(name)
    "Good night, #{name}"
  end
puts say_goodnight3('Ma')



****************************************************************************************


a = [ 1, 'cat', 3.14 ]   # array with three elements
# access the first element
puts a[0]
puts a[1]
puts a[2]
# set the third element
a[2] = nil
# dump out the array
puts a

puts "**********************************************"

b =%w[cat dog ant]
puts b


inst_section = {
    'cello'     => 'string',
    'clarinet'  => 'woodwind',
    'drum'      => 'percussion',
    'oboe'      => 'woodwind',
    'trumpet'   => 'brass',
    'violin'    => 'string'
}

#puts inst_section

puts inst_section['oboe']
puts inst_section['cello']
puts inst_section['bassoon']


histogram = Hash.new(0)
puts   histogram['key1']
puts   histogram['key1'] = histogram['key1'] + 1
puts   histogram['key1']

count = 9
if count > 10
  puts "Try again"
else
  puts "You lose"
end



num_pallets = 11
weight = 1

while weight < 10 and num_pallets <= 15  
  weight += 1
  num_pallets += 1
  puts num_pallets
  puts weight
end



square = 2
while square < 1000
   square = square*square
end

puts square


def three_times
yield
yield
yield
end

three_times {puts "Hello"}

[1,3,5].each {|i| puts i}


****************************************************************************************












class Person
def initialize(name, gender, age)
        @name = name
        @gender = gender
@age = age
end
end

class Person
                def name
                        @name
                end

                def gender
                        @gender
                end

                def age
                        @age
                end
end



people = Person.new('Tom', 'male', 15)
  
puts people.name
puts people.gender
puts people.age

class Person
                def name=(name)
                        @name=name
                end

                def gender=(gender)
                        @gender=gender
                end

                def age=(age)
                        @age=age
                end
end


people.name        = "Henry"
people.gender        = "male"
people.age                = 25



puts people.name
puts people.gender
puts people.age



class Student < Person
        def initialize(name, gender, age, school)
                @name = name
                @gender = gender
                @age = age
                @school = school
        end
end











class Base
                def meth(info)
                        puts "This is Base #{info}"
                end
end

class Derived < Base
                def meth(info)
                        puts "This is derived #{info}"
                        super
                end
end


derived = Derived.new

derived.meth("haha")

TOP

ruby -e 'puts "David".reverse'

TOP

你想要倒过来看一个单词。以下是以一个命令来快速实现此功能的代码。

ruby -e 'print "Enter a name: "; print gets.reverse'

TOP

从文件中读入一个数,并将其从摄氏转换到华氏。(有时从文件中读数据确实比这要麻烦一些,但该例子展现了基本的操作。)并将华氏转换结果保存到另一个文件中。

puts "Reading temperature from temp.dat file...."
c = File.read("temp.dat")

f =(c.to_i * 9/5) + 32

print "The result is:"
print f

fh = File.new("temp.out","w")
fh.puts f
fh.close

TOP

irb

irb(main)>Config::CONFIG["bindir"]

该请求显示Ruby可执行文件(包括ruby和irb)的安装目录——bindir。获取其他信息需要用别的术语来替代irb命令中的bindir。但是每一次都会使用相同的基本公式:Config::CONFIG ["term"]。

TOP

Date Format meaning:   
  
      %a - The abbreviated weekday name ("Sun")   
      %A - The full weekday name ("Sunday")   
      %b - The abbreviated month name ("Jan")   
      %B - The full month name ("January")   
      %c - The preferred local data and time representation   
      %d - Day of the month (01..31)   
      %H - Hour of the day, 24-hour clock (00..23)   
      %I - Hour of the day, 12-hour clock (01..12)   
      %j - Day of the year (001..366)   
      %m - Month of the year (01..12)   
      %M - Minute of the hour (00..59)   
      %p - Meridian indicator ("AM" or "PM")   
      %S - Second of the minute (00..60)   
      %U - Week number of the current year, starting with the first Sunday as the first   
              day of the first week (00..53)   
      %W - Week number of the current year, starting with the first Monday as the first   
              day of the first week (00..53)   
      %w - Day of the week (Sunday is 0, 0..6)   
      %x - Preferred representation for the date alone, no time   
      %X - Preferred representation for the time alone, no date   
      %y - Year without a century (00..99)   
      %Y - Year with century   
      %Z - Time zone name   
      %% - Literal "%" character   
  
       t = Time.now   
       t.strftime("Printed on %m/%d/%Y")  #=> "Printed on 04/09/2003"  
       t.strftime("at %I:%M%p)            #=> "at 08:56AM"

TOP

a=[["ABC","1"],["DEF","2"],["GHI","3"]]

a.map!{|x|
  [x[0],x[1].to_i]
}

pp a


a=[["ABC","3"],["DEF","5"],["GHI","2"]]

sum=0
a.map!{|x|
  sum +=x[1].to_i
  [x[0],x[1].to_i,sum]
}

pp a


a = [10, 20, 30, 40, 50]
p a.collect {|x| x*10} #=> [100, 200, 300, 400, 500]
p a #=> [10, 20, 30, 40, 50]

p a.map {|x| x*10} #=> [100, 200, 300, 400, 500]
p a #=> [10, 20, 30, 40, 50]

a.collect! {|x| x/10} #=> [1, 2, 3, 4, 5]
p a #=> [1, 2, 3, 4, 5]

a = [["vine", 2, 500], ["orange", 3, 100], ["apple", 10, 50]]
p a.map {|x| [x[0], x[1]*x[2]]} #=> [["vine", 1000], ["orange", 300], ["apple", 500]]

TOP

ruby 怎么利用正则表达式在把一个字符串数组中的数字放到一个数组中?


给定一个类似下面格式的字符串
复制内容到剪贴板
代码:
"a10 b20 c25 d40"  
写一段代码把它转化成hash
复制内容到剪贴板
代码:
{'a' => 10, 'b' => 20, 'c' => 25, 'd' => 40 }
http://www.rubyinside.com/21-ruby-tricks-902.html

http://www.namaraii.com/rubytips/

答案是:
复制内容到剪贴板
代码:
pp Hash[*(str.scan(/(\w)(\d+)/).map {|k, v| [k, v.to_i] }.flatten)]

TOP

复制内容到剪贴板
代码:
pp Hash[*(str.scan(/(\w)(\d+)/).map {|k, v| [k, v.to_i] }.flatten)]
我ruby不熟,这一句话理解起来要10分钟。 自己写要30分钟还不一定对。
有什么好的办法?
(比如用javascript 来实现这个功能, 可能要写20句话,但是可以在5分钟内实现。)
是不是熟练者写这一句话只要1分钟?

(项目开发中觉得应该少写这种一句话或者2句话的代码写法),参考下帖.“魔幻语言”和“简约语言“
http://www.j-kanban.com/bbs/thread-5148-1-1.html

TOP

回复 #9 robotfish 的帖子

言之有理,实际开发的时候是不应该写得很虚幻的,哈哈。

不过我看这句代码还算通俗易懂。

TOP

回复 #10 admin 的帖子

你是类似代码看太多了吧。
这句的可读性。。。

C和JAVA都有a?b:c的语法,但是编码规范都不提倡用这个而推荐使用if。
我觉得多写几行让所有人都容易看懂比一句就搞定这种高技术含量的语句要好。
尚能饭

TOP

引用:
原帖由 sabbath 于 2008-6-16 15:25 发表
你是类似代码看太多了吧。
这句的可读性。。。

C和JAVA都有a?b:c的语法,但是编码规范都不提倡用这个而推荐使用if。
我觉得多写几行让所有人都容易看懂比一句就搞定这种高技术含量的语句要好。
针对这道题,首先正则表达式是必须的,其它方式似乎很难实现。

其次 map ,hash迭代是ruby的利器 ,熟了就知道好用了。

只有flatten稍微生僻点,其实是防止递归的each。

TOP

01 #does ruby guy notice about this pain?
02 #翻转斜杠
03 def reverse_slash(str)
04     str.gsub(/\//) { |x| "\\" }
05 end
06
07 #加上双引号
08 #double-quote str
09 def dquote(str)
10     "\"#{str}\""
11 end
12
13 #execute and wait for each line
14 #执行命令行工具并捕获命令行输出
15 def execute_and_watch(str)
16     putsflush "  command:#{str}"
17     IO.popen(str).each {|line| yield line}
18 end
19
20 #log to the $stderr
21 #输出到ERR,立即刷新
22 def logerr(str)
23     #we might need to set the error log file and output log file in the future
24     $stderr.putsflush "ERROR! " + str
25 end
26
27 #puts to the $stdout and flush
28 def putsflush(*str)
29     puts *str
30     $stdout.flush
31 end

TOP

发新话题