I am a beginner in Ruby. Could someone help me with this?
I want to call a method within ""
def callme
"this string" # this is usually a path that I want to source from a single location
end
v= "string + callme "
how do I call the function within quotes here? The quotes are essential for my code.
You can use string interpolation / concatenation:
def hi
'Hello'
end
def world
'World'
end
# Concatenation
hi + ' ' + world #=> "Hello World"
# Interpolation
"#{hi} #{world}" #=> "Hello World"
See this answer for more details
If I understand correctly, what you are looking for is string interpolation. The syntax for this is #{...}, like so:
v= "string + #{callme} "
This sets the variable v to "string + this string ".
Reference
The proper way to use string interpolation in Ruby is as follows:
name = "Ned Stark"
puts "Hello there, #{name}" #=> "Hello there, Ned Stark"
That is the way I intend to always use it.
However, I've noticed something odd in Ruby's string interpolation. I've noticed that string interpolation works in Ruby without the curly braces in regards to instance variables. For example:
#name = "Ned Stark"
puts "Hello there, ##name" #=> "Hello there, Ned Stark"
And that trying the same thing as a non-instance variable does not work.
name = "Ned Stark"
puts "Hello, there, #name" #=> "Hello there, #name"
I've tried this with success in both 1.9.2 and 1.8.7.
Why does this work? What is the interpreter doing here?
According to The Ruby Programming Language by Flanagan and Matsumoto:
When the expression to be interpolated into the string literal is simply a reference to a global, instance or class variable, then the curly braces may be omitted.
So the following should all work:
#var = "Hi"
puts "##var there!" #=> "Hi there!"
##var = "Hi"
puts "###var there!" #=> "Hi there!"
$var = "Hi"
puts "#$var there!" #=> "Hi there!"
I have the following program:
class Matcher
include Enumerable
def initialize(string, match)
#string = string
#match = match
end
def each
#string.scan(/[##match]/) do |pattern|
yield pattern
end
end
end
mch = Matcher.new("the quickbrown fox", "aeiou")
puts mch.inject {|x, n| x+n}
It is supposed to match the characters, aeiou with the string the quickbrown fox
No matter what I put as the pattern, it oddly prints out the characters: thc. What's going on?
#string.scan(/[##match]/) do |pattern| is incorrect. #{#match} is what you're looking for.
I'm trying to convert an all-uppercase string in Ruby into a lower case one, but with each word's first character being upper case. Example:
convert "MY STRING HERE" to "My String Here".
I know I can use the .downcase method, but that would make everything lower case ("my string here"). I'm scanning all lines in a file and doing this change, so is there a regular expression I can use through ruby to achieve this?
Thanks!
If you're using Rails (really all you need is ActiveSupport, which is part of Rails), you can use titleize:
"MY STRING HERE".titleize
# => "My String Here"
If you're using plain Ruby but don't mind loading a small amount of ActiveSupport you can require it first:
require 'active_support/core_ext/string/inflections'
# => true
"MY STRING HERE".titleize
# => "My String Here"
N.B. By default titleize doesn't handle acronyms well and will split camelCaseStrings into separate words. This may or may not be desirable:
"Always use SSL on your iPhone".titleize
# => "Always Use Ssl On Your I Phone"
You can (partially) address this by adding "acronyms":
require 'active_support/core_ext/string/inflections' # If not using Rails
ActiveSupport::Inflector.inflections do |inflect|
inflect.acronym 'SSL'
inflect.acronym 'iPhone'
end
"Always use SSL on your iPhone".titleize
# => "Always Use SSL On Your IPhone"
For those who speak the Queen's English (or who struggle to spell titleize), there's no .titleise alias but you can use .titlecase instead.
"HELLO WORLD HOW ARE YOU".gsub(/\w+/) do |word|
word.capitalize
end
#=> "Hello World How Are You"
While trying to come up with my own method (included below for reference), I realized that there's some pretty nasty corner cases. Better just use the method already provided in Facets, the mostest awesomest Ruby library evar:
require 'facets/string/titlecase'
class String
def titleize
split(/(\W)/).map(&:capitalize).join
end
end
require 'test/unit'
class TestStringTitlecaseAndTitleize < Test::Unit::TestCase
def setup
#str = "i just saw \"twilight: new moon\", and man! it's crap."
#res = "I Just Saw \"Twilight: New Moon\", And Man! It's Crap."
end
def test_that_facets_string_titlecase_works
assert_equal #res, #str.titlecase
end
def test_that_my_own_broken_string_titleize_works
assert_equal #res, #str.titleize # FAIL
end
end
If you want something that more closely complies to typical writing style guidelines (i.e. does not capitalize words like "and"), there are a couple of "titleize" gems on GitHub.
From ActiveSupport
"MY STRING HERE".gsub(/\b('?[a-z])/) { $1.capitalize }
If you are using Rails/ActiveSupport, the method is already available for free.
string = "MY STRING HERE"
string.split(" ").map {|word| word.capitalize}.join(" ")
The way this works:
The .split(" ") splits it on spaces, so now we have an array that looks like ["my", "string", "here"]. The map call iterates over each element of the array, assigning it to temporary variable word, which we then call capitalize on. Now we have an array that looks like ["My", "String", "Here"], and finally we turn that array back into a string by joining each element with a space (" ").
"MY STRING HERE".titlecase
Does the job (it's a method in the Rails gem, however)
http://apidock.com/rails/String/titlecase
Unicode-aware titlecase for Ruby 2.4.0+:
class String
def titlecase
split(/([[:alpha:]]+)/).map(&:capitalize).join
end
end
>> "я только что посмотрел \"леди исчезает\", и это чума!".titlecase
=> "Я Только Что Посмотрел \"Леди Исчезает\", И Это Чума!"
(based on https://stackoverflow.com/a/1792102/788700)
To catch any edge case such as:
str = "rUby on rAils"
Don't use:
str.titleize
Output: R Uby On R Ails
Use instead:
str.downcase.titleize
Output: Ruby On Rails
I've try to improve code... ready for critics and suggestions.
class Book
attr_accessor :title
def title=(new_title)
notcap=%w(and the a in of an)
str=''
new_title.gsub(/(\w|\s)\w+/) do |word|
word.strip!
if not notcap.include? word
word.capitalize!
end
str += ' ' + word
end
str.strip!
str = str[0].upcase + str[1..-1]
#title = str
end
end
The ruby core itself has no support to convert a string from upper (word) case to capitalized word case.
So you need either to make your own implementation or use an existing gem.
There is a small ruby gem called lucky_case which allows you to convert a string from any of the 10+ supported cases to another case easily:
require 'lucky_case'
# to get capital word case as string
LuckyCase.capital_word_case('MY STRING HERE') # => 'My String Here'
# or the opposite way
LuckyCase.upper_word_case('Capital Word Case') # => 'MY STRING HERE'
You can even monkey patch the String class if you want to:
require 'lucky_case/string'
'MY STRING HERE'.capital_word_case # => 'My String Here'
'MY STRING HERE'.capital_word_case! # => 'My String Here' and overwriting original
Have a look at the offical repository for more examples and documentation:
https://github.com/magynhard/lucky_case
Capitalizes every word in a sentence using ruby, without regex.. because unfortunately those scare me
class Book
attr_accessor :title
def title=(new_title)
result = []
words = new_title.split(' ')
words.each do |word|
capitalized = word[0].upcase + word[1..word.length].downcase
result.push(capitalized)
end
#title = result.join(' ')
end
end
How do I make \n actually work in my output? At the moment it just writes it all in 1 long block. Thanks for any help
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
#new = ''
playlist_name = gets.chomp + '.m3u'
music.each do |z|
#new += z + '\n'
end
File.open playlist_name, 'w' do |f|
f.write #new
end
Use "\n" instead of '\n'
I would like to share my experience with \n
I came to notice that "\n" works as-
puts "\n\n" // to provide 2 new lines
but not
p "\n\n"
also
puts '\n\n'
Doesn't works.
Hope will work for you!!
You can do this all in the File.open block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open playlist_name, 'w' do |f|
music.each do |z|
f.puts z
end
end
Actually you don't even need the block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open(playlist_name, 'w').puts(music)
For me it didn't work with adding "\n" to the end of an existing argument to puts, so as a workaround I called print on the next line with "\n" as an argument, although I suppose I could have just called puts again.
This did not produce the desired result:
puts "Coach says: #{coach_answer(user_input)}\n"
But this did:
puts "Coach says: #{coach_answer(user_input)}"
print "\n"