-1

这是一个简单的 Ruby 代码,但我不知道如何理解和使用它。

def string_length_interpolater(incoming_string)
  "The string you just gave me has a length of #{incoming_string.length}"
end

有人可以帮我完成这个过程吗?

4

1 回答 1

4

它返回一个带有所示短语的字符串(“The string you...”)加上传入的字符串长度,例如

string_length_interpolater('Hi')

=>  "The string you just gave me has a length of 2" 

string_length_interpolater('Hi There')

=>  "The string you just gave me has a length of 8" 

string_length_interpolater('123456789')

=>  "The string you just gave me has a length of 9" 

string_length_interpolater('Hello Ruby')

=>  "The string you just gave me has a length of 10" 

如您所见,该方法只是返回该文本-“您刚刚给我的字符串有一个长度”以及传入的参数的长度。#{}双引号内的意思是计算出红宝石值,然后在字符串。

它也与

def string_length_interpolater(incoming_string)
  "The string you just gave me has a length of " + incoming_string.length
end

当输出变得复杂时 - 在各个点带有 'ruby 输出的字符串,使用 doubles qoutes ('interpolation') 方法变得更容易,例如:

"From #{start} to #{end} the #{person} used a #{tool}"

通常比读/写/维护更容易

"From " + start + " to " + end + " the " + person + " used a " + tool  

补充:如果您还想显示字符串本身的值,您可以使用:

def string_and_length(nm)
  "Hello there #{nm}, did you know your name is #{nm.length} letters long?"
end
于 2013-10-31T02:11:20.233 回答